title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Default FirebaseApp is not initialized in this process com.forgottenitem.myevent1. Make sure to call FirebaseApp.initializeApp(Context) first
|
<p>I am new to android. Kindly assist me with this error message:</p>
<pre><code>2021-07-03 14:07:51.800 5006-5006/com.real.myevent1 D/AndroidRuntime: Shutting down VM
2021-07-03 14:07:51.803 5006-5006/com.real.myevent1 E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.real.myevent1/com.real.myevent1.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.forgottenitem.myevent1. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.forgottenitem.myevent1. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@19.3.0:184)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth@@19.3.1:1)
at com.real.myevent1.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
2021-07-03 14:52:35.108 5997-5997/com.real.myevent1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.real.myevent1, PID: 5997
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.real.myevent1/com.real.myevent1.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.real.myevent1. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.real.myevent1. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@19.3.0:184)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth@@19.3.1:1)
at com.real.myevent1.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-07-03 14:52:35.218 5997-5997/com.real.myevent1 I/Process: Sending signal. PID: 5997 SIG: 9
</code></pre>
| 3 | 2,127 |
How to make images change a little quicker?
|
<p>My code works just fine but for some reason when you click on the play button it takes a bit longer to switch over to the pause sign, and occasionally it takes a bit longer for the pause button to go to the play button. I also have one more question, when you click on the rain and beach icon there's a blue square border that I didn't remember putting, how do you remove it?
Thanks, Love2code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Meditation App</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<style>
*{
margin:0;
padding:0;
box-sizing:border-box;
}
.app{
height:100vh;
display:flex;
justify-content:space-evenly;
align-items:center;
}
.time-select,.sound-picker,.player-container{
height:80%;
flex:1;
display:flex;
flex-direction:column;
justify-content:space-evenly;
align-items:center;
}
.player-container{
position:relative;
}
.player-container svg{
position:absolute;
height:50%;
top:50%;
left:50%;
transform:translate(-50%,-50%);
pointer-events:none;
}
.time-display{
position:absolute;
bottom:10%;
color:white;
font-size:50px;
}
video{
position:fixed;
top:0%;
left:0%;
width:100%;
z-index:-10;
}
.time-select button,
.sound-picker button{
color:white;
width:30%;
height:10%;
background:none;
border:2px solid white;
cursor:pointer;
border-radius:5px;
font-size:20px;
transition:all 0.5s ease;
}
.time-select button:hover{
color:black;
background:white;
}
.sound-picker button{
border:none;
height:120px;
width:120px;
border-radius:50%;
}
.sound-picker button:nth-child(1){
background:#4972a1;
}
.sound-picker button:nth-child(2){
background:#a14f49;
}
.sound-picker:focus{
outline: none;
}
</style>
</head>
<body>
<div class="app">
<div class="vid-container">
<video Loop>
<source src="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"/>
</video>
</div>
<div class="time-select">
<button data-time="120">2 Minutes</button>
<button data-time="300">5 Minutes</button>
<button data-time="600">10 Minutes</button>
</div>
<div class="player-container">
<audio class="song">
<source src="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1"></source>
</audio>
<img src="https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1" class="play-container" alt="">
<svg class="track-outline"
width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="226.5" cy="226.5" r="216.5" stroke="white" stroke-width="20"/>
</svg>
<svg class="moving-outline"
width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="226.5" cy="226.5" r="216.5" stroke="#018EBA" stroke-width="20"/>
</svg>
<h3 class="time-display">0:00</h3>
</div>
<div class="sound-picker">
<button data-sound="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1" data-video="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"><img src="https://i.ibb.co/8BspYTV/rain-1.png"></button>
<button data-sound="https://www.dropbox.com/s/6k9nauf2ffyvfuu/beach.mp3?raw=1"
data-video="https://www.dropbox.com/s/tsdd86bxmax32jp/beach.mp4?raw=1"><img src="https://i.ibb.co/T0xw4k7/sun-umbrella.png"></button>
</div>
</body>
<script>
const app = () => {
const song = document.querySelector(".song");
const play = document.querySelector(".play-container");
const outline = document.querySelector(".moving-outline circle");
const video = document.querySelector(".vid-container video");
//Sounds
const sounds = document.querySelectorAll(".sound-picker button");
//Time Display
const timeDisplay = document.querySelector(".time-display");
//Get length of the outside
const outlineLength = outline.getTotalLength();
//Duration
let fakeDuration = 600;
outline.style.strokeDasharray = outlineLength;
outline.style.strokeDashoffset = outlineLength;
//play sounds
play.addEventListener("click", () => {
checkPlaying(song);
});
//stop and play the sounds
const checkPlaying = song =>{
if(song.paused){
song.play();
video.play();
play.src = 'https://www.dropbox.com/s/3zvnjkebwt1sjgq/download%20%283%29.svg?raw=1';
}else{
song.pause();
video.pause();
play.src = 'https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1';
}
}
};
app();
</script>
</html></code></pre>
</div>
</div>
</p>
| 3 | 3,061 |
Horizontal list not working
|
<p>I am trying to make use of Bootstrap horizontal lists, but it’s not working correctly. How can I fix this issue?</p>
<p>I am trying to get this:<br>
<a href="https://i.stack.imgur.com/zzBFi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zzBFi.png" alt="example"></a></p>
<p>Currently, I have this:<br>
<a href="https://i.stack.imgur.com/cfoZN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfoZN.png" alt="issue"></a></p>
<p>Here is my code:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-xs, .btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 73px;
height: 38px;
background-color: #53585f;
color: white;
font-family: sans-serif;
}
.btn-default:hover {
background-color: #b89981;
color: white;
}
ul.list-group:after {
clear: both;
display: block;
content: "";
}
.list-group-item {
float: left;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
width: 73px;
}
.padding20 {
padding : 10px;
}
.textbox {
line-height: 24px;
}
.liststyle1 {
margin: 0;
list-style: none;
margin-top: 10px;
line-height: 28px;
color: #309be8;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<h2>dsd</h2>
<button type="button" class="btn btn-default btn-xs">Total</button>
<button type="button" class="btn btn-default btn-xs">Check-Out</button>
<button type="button" class="btn btn-default btn-xs">Check-In</button>
<button type="button" class="btn btn-default btn-xs">Alerts</button>
<button type="button" class="btn btn-default btn-xs">Tentative</button>
</div>
<div class="container list-top">
<ul class="list-group">
<li class="list-group-item">12Bookings
</li>
<li class="list-group-item">Dapibus </li>
<li class="list-group-item">Morbi</li>
<li class="list-group-item">Porta</li>
<li class="list-group-item">Vestib</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,137 |
How to pass the submitted form data along with multipartfile(image) upload and save the data to a javabean on the controller end Spring MVC
|
<pre><code>My Html Content
<form role="form" name="frm1" action="http://localhost:8080/aricloud/rest/usermgmt/signup" id="signup" method="POST" enctype="multipart/form-data">
<div class="form-group">`enter code here`
<label for="username">Login Name</label>
<input type="text" class="form-control" name="userName" id="username" placeholder="Enter Username" value="vindu525">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="passwd" placeholder="Password" value="12345">
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password</label>
<input type="password" class="form-control" name="confirmPassword" id="confirmpasswd" placeholder="Please enter Password again" value="12345">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="emailID" id="emailID" placeholder="Enter email" value="vindu525@gmail.com">
</div>
<div class="form-group">
<label for="mobile">Mobile No</label>
<input type="text" class="form-control" name="mobileNumber" id="mobileNumber" placeholder="Enter email" value="9584315174">
</div>
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" name="country" id="country" placeholder="Enter country" value="india">
</div>
<div class="form-group">
<label for="country">File Upload</label>
<input type="file" class="form-control" name="image" id="image" >
</div>
<input type="hidden" class="form-control" name="userAvatar" id="userAvatar" value="null"/>
<button id="regsubmit" type="submit" class="btn btn-default">Submit</button>
</form>
</code></pre>
<hr>
<p>My Controller </p>
<pre><code>public ResponseEntity<String> addUser(@RequestBody UserDetailsBean user,
@Context HttpServletRequest request,
@Context HttpServletResponse response
) {
//File handling and other logic goes here
}
</code></pre>
<hr>
<p>UserDetailsBean contains the setter and getter methods for all the form data including the image</p>
<hr>
<p>When I post the data I get the below error
415 (Unsupported Media Type)</p>
<p>Though the individual file and content upload works when I try to integrate the multipartfile with the userdetails bean it gives me an error.</p>
| 3 | 1,047 |
Weird error in phpmyadmin using virtualbox ubuntu
|
<p>I have setup a virtualbox and vagrant using puphpet. Everything is working fine except for phpmyadmin. I have installed everything correctly but when I try to access <a href="http://ip_address/phpmyadmin" rel="nofollow noreferrer">http://ip_address/phpmyadmin</a> I receive this text:</p>
<pre><code>addJSON( 'options', PMA_RecentTable::getInstance()->getHtmlSelectOption() );
exit; } if ($GLOBALS['PMA_Config']->isGitRevision()) { if (isset($_REQUEST['git_revision']) && $GLOBALS['is_ajax_request'] == true) { PMA_printGitRevision(); exit; } echo '
'; } // Handles some variables that may have been sent by the calling script $GLOBALS['db'] = ''; $GLOBALS['table'] = ''; $show_query = '1'; // Any message to display? if (! empty($message)) { echo PMA_Util::getMessage($message); unset($message); } $common_url_query = PMA_generate_common_url('', ''); // when $server > 0, a server has been chosen so we can display // all MySQL-related information if ($server > 0) { include 'libraries/server_common.inc.php'; include 'libraries/StorageEngine.class.php'; // Use the verbose name of the server instead of the hostname // if a value is set $server_info = ''; if (! empty($cfg['Server']['verbose'])) { $server_info .= htmlspecialchars($cfg['Server']['verbose']); if ($GLOBALS['cfg']['ShowServerInfo']) { $server_info .= ' ('; } } if ($GLOBALS['cfg']['ShowServerInfo'] || empty($cfg['Server']['verbose'])) { $server_info .= PMA_DBI_get_host_info(); } if (! empty($cfg['Server']['verbose']) && $GLOBALS['cfg']['ShowServerInfo']) { $server_info .= ')'; } $mysql_cur_user_and_host = PMA_DBI_fetch_value('SELECT USER();'); // should we add the port info here? $short_server_info = (!empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host']); } echo '
' . "\n"; echo '
'; if ($server > 0 || count($cfg['Servers']) > 1 ) { echo '
'; echo '
' . __('General Settings') . '
'; echo '
'; /** * Displays the MySQL servers choice form */ if ($cfg['ServerDefault'] == 0 || (! $cfg['NavigationDisplayServers'] && (count($cfg['Servers']) > 1 || ($server == 0 && count($cfg['Servers']) == 1) ) ) ) { echo '
'; include_once 'libraries/select_server.lib.php'; echo PMA_Util::getImage('s_host.png') . " " . PMA_selectServer(true, true); echo '
'; } /** * Displays the mysql server related links */ if ($server > 0 && ! PMA_DRIZZLE) { include_once 'libraries/check_user_privileges.lib.php'; // Logout for advanced authentication if ($cfg['Server']['auth_type'] != 'config') { if ($cfg['ShowChgPassword']) { $conditional_class = 'ajax'; PMA_printListItem( PMA_Util::getImage('s_passwd.png') . " " . __('Change password'), 'li_change_password', 'user_password.php?' . $common_url_query, null, null, 'change_password_anchor', "no_bullets", $conditional_class ); } } // end if echo '
'; echo '
' . "\n" . PMA_generate_common_hidden_inputs(null, null, 4, 'collation_connection') . ' ' . "\n" . ' '. PMA_Util::getImage('s_asci.png') . " " . __('Server connection collation') . "\n" // put the doc link in the form so that it appears on the same line . PMA_Util::showMySQLDocu( 'MySQL_Database_Administration', 'Charset-connection' ) . ': ' . "\n" . ' ' . "\n" . PMA_generateCharsetDropdownBox( PMA_CSDROPDOWN_COLLATION, 'collation_connection', 'select_collation_connection', $collation_connection, true, 4, true ) . '
' . "\n" . '
' . "\n"; } // end of if ($server > 0 && !PMA_DRIZZLE) echo '
'; echo '
'; } echo '
'; echo '
' . __('Appearance Settings') . '
'; echo '
'; // Displays language selection combo if (empty($cfg['Lang']) && count($GLOBALS['available_languages']) > 1) { echo '
'; include_once 'libraries/display_select_lang.lib.php'; echo PMA_Util::getImage('s_lang.png') . " " . PMA_getLanguageSelectorHtml(); echo '
'; } // ThemeManager if available if ($GLOBALS['cfg']['ThemeManager']) { echo '
'; echo PMA_Util::getImage('s_theme.png') . " " . $_SESSION['PMA_Theme_Manager']->getHtmlSelectBox(); echo '
'; } echo '
'; echo PMA_Config::getFontsizeForm(); echo '
'; echo '
'; // User preferences if ($server > 0) { echo '
'; PMA_printListItem( PMA_Util::getImage('b_tblops.png')." " .__('More settings'), 'li_user_preferences', 'prefs_manage.php?' . $common_url_query, null, null, null, "no_bullets" ); echo '
'; } echo '
'; echo '
'; echo '
'; if ($server > 0 && $GLOBALS['cfg']['ShowServerInfo']) { echo '
'; echo '
' . __('Database server') . '
'; echo '
' . "\n"; PMA_printListItem( __('Server') . ': ' . $server_info, 'li_server_info' ); PMA_printListItem( __('Server type') . ': ' . PMA_Util::getServerType(), 'li_server_type' ); PMA_printListItem( __('Server version') . ': ' . PMA_MYSQL_STR_VERSION . ' - ' . PMA_MYSQL_VERSION_COMMENT, 'li_server_version' ); PMA_printListItem( __('Protocol version') . ': ' . PMA_DBI_get_proto_info(), 'li_mysql_proto' ); PMA_printListItem( __('User') . ': ' . htmlspecialchars($mysql_cur_user_and_host), 'li_user_info' ); echo '
'; echo ' ' . __('Server charset') . ': ' . ' '; if (! PMA_DRIZZLE) { echo ' ' . $mysql_charsets_descriptions[$mysql_charset_map['utf-8']] . "\n"; } echo ' (' . $mysql_charset_map['utf-8'] . ')' . "\n" . ' ' . "\n" . '
' . "\n"; echo '
'; echo '
'; } if ($GLOBALS['cfg']['ShowServerInfo'] || $GLOBALS['cfg']['ShowPhpInfo']) { echo '
'; echo '
' . __('Web server') . '
'; echo '
'; if ($GLOBALS['cfg']['ShowServerInfo']) { PMA_printListItem($_SERVER['SERVER_SOFTWARE'], 'li_web_server_software'); if ($server > 0) { $client_version_str = PMA_DBI_get_client_info(); if (preg_match('#\d+\.\d+\.\d+#', $client_version_str) && in_array($GLOBALS['cfg']['Server']['extension'], array('mysql', 'mysqli')) ) { $client_version_str = 'libmysql - ' . $client_version_str; } PMA_printListItem( __('Database client version') . ': ' . $client_version_str, 'li_mysql_client_version' ); $php_ext_string = __('PHP extension') . ': ' . $GLOBALS['cfg']['Server']['extension'] . ' ' . PMA_Util::showPHPDocu( 'book.' . $GLOBALS['cfg']['Server']['extension'] . '.php' ); PMA_printListItem( $php_ext_string, 'li_used_php_extension' ); } } if ($cfg['ShowPhpInfo']) { PMA_printListItem( __('Show PHP information'), 'li_phpinfo', 'phpinfo.php?' . $common_url_query, null, '_blank' ); } echo '
'; echo '
'; } echo '
'; echo '
phpMyAdmin
'; echo '
'; $class = null; // We rely on CSP to allow access to http://www.phpmyadmin.net, but IE lacks // support here and does not allow request to http once using https. if ($GLOBALS['cfg']['VersionCheck'] && (! $GLOBALS['PMA_Config']->get('is_https') || PMA_USR_BROWSER_AGENT != 'IE') ) { $class = 'jsversioncheck'; } PMA_printListItem( __('Version information') . ': ' . PMA_VERSION, 'li_pma_version', null, null, null, null, $class ); PMA_printListItem( __('Documentation'), 'li_pma_docs', PMA_Util::getDocuLink('index'), null, '_blank' ); PMA_printListItem( __('Wiki'), 'li_pma_wiki', PMA_linkURL('http://wiki.phpmyadmin.net/'), null, '_blank' ); // does not work if no target specified, don't know why PMA_printListItem( __('Official Homepage'), 'li_pma_homepage', PMA_linkURL('http://www.phpMyAdmin.net/'), null, '_blank' ); PMA_printListItem( __('Contribute'), 'li_pma_contribute', PMA_linkURL('http://www.phpmyadmin.net/home_page/improve.php'), null, '_blank' ); PMA_printListItem( __('Get support'), 'li_pma_support', PMA_linkURL('http://www.phpmyadmin.net/home_page/support.php'), null, '_blank' ); PMA_printListItem( __('List of changes'), 'li_pma_changes', PMA_linkURL('changelog.php'), null, '_blank' ); ?>
1) { trigger_error( __('You have enabled mbstring.func_overload in your PHP configuration. This option is incompatible with phpMyAdmin and might cause some data to be corrupted!'), E_USER_WARNING ); } /** * Nijel: mbstring is used for handling multibyte inside parser, so it is good * to tell user something might be broken without it, see bug #1063149. */ if (! @extension_loaded('mbstring')) { trigger_error( __('The mbstring PHP extension was not found and you seem to be using a multibyte charset. Without the mbstring extension phpMyAdmin is unable to split strings correctly and it may result in unexpected results.'), E_USER_WARNING ); } /** * Check whether session.gc_maxlifetime limits session validity. */ $gc_time = (int)@ini_get('session.gc_maxlifetime'); if ($gc_time < $GLOBALS['cfg']['LoginCookieValidity'] ) { trigger_error( __('Your PHP parameter [a@http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime@_blank]session.gc_maxlifetime[/a] is lower than cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.'), E_USER_WARNING ); } /** * Check whether LoginCookieValidity is limited by LoginCookieStore. */ if ($GLOBALS['cfg']['LoginCookieStore'] != 0 && $GLOBALS['cfg']['LoginCookieStore'] < $GLOBALS['cfg']['LoginCookieValidity'] ) { trigger_error( __('Login cookie store is lower than cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.'), E_USER_WARNING ); } /** * Check if user does not have defined blowfish secret and it is being used. */ if (! empty($_SESSION['auto_blowfish_secret']) && empty($GLOBALS['cfg']['blowfish_secret']) ) { trigger_error( __('The configuration file now needs a secret passphrase (blowfish_secret).'), E_USER_WARNING ); } /** * Check for existence of config directory which should not exist in * production environment. */ if (file_exists('config')) { trigger_error( __('Directory [code]config[/code], which is used by the setup script, still exists in your phpMyAdmin directory. You should remove it once phpMyAdmin has been configured.'), E_USER_WARNING ); } if ($server > 0) { $cfgRelation = PMA_getRelationsParam(); if (! $cfgRelation['allworks'] && $cfg['PmaNoRelation_DisableWarning'] == false ) { $msg = PMA_Message::notice(__('The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click %shere%s.')); $msg->addParam( '', false ); $msg->addParam('', false); /* Show error if user has configured something, notice elsewhere */ if (!empty($cfg['Servers'][$server]['pmadb'])) { $msg->isError(true); } $msg->display(); } // end if } /** * Warning about different MySQL library and server version * (a difference on the third digit does not count). * If someday there is a constant that we can check about mysqlnd, * we can use it instead of strpos(). * If no default server is set, PMA_DBI_get_client_info() is not defined yet. * Drizzle can speak MySQL protocol, so don't warn about version mismatch for * Drizzle servers. */ if (function_exists('PMA_DBI_get_client_info') && !PMA_DRIZZLE && $cfg['ServerLibraryDifference_DisableWarning'] == false ) { $_client_info = PMA_DBI_get_client_info(); if ($server > 0 && strpos($_client_info, 'mysqlnd') === false && substr(PMA_MYSQL_CLIENT_API, 0, 3) != substr(PMA_MYSQL_INT_VERSION, 0, 3) ) { trigger_error( PMA_sanitize( sprintf( __('Your PHP MySQL library version %s differs from your MySQL server version %s. This may cause unpredictable behavior.'), $_client_info, substr( PMA_MYSQL_STR_VERSION, 0, strpos(PMA_MYSQL_STR_VERSION . '-', '-') ) ) ), E_USER_NOTICE ); } unset($_client_info); } /** * Warning about Suhosin */ if ($cfg['SuhosinDisableWarning'] == false && @ini_get('suhosin.request.max_value_length') // warn about Suhosin only if its simulation mode is not enabled && @ini_get('suhosin.simulation') == '0' ) { trigger_error( sprintf( __('Server running with Suhosin. Please refer to %sdocumentation%s for possible issues.'), '[doc@faq1-38]', '[/doc]' ), E_USER_WARNING ); } /** * Warning about mcrypt. */ if (! function_exists('mcrypt_encrypt') && ! $GLOBALS['cfg']['McryptDisableWarning'] ) { PMA_warnMissingExtension('mcrypt'); } /** * Warning about incomplete translations. * * The data file is created while creating release by ./scripts/remove-incomplete-mo */ if (file_exists('libraries/language_stats.inc.php')) { include 'libraries/language_stats.inc.php'; /* * This message is intentionally not translated, because we're * handling incomplete translations here and focus on english * speaking users. */ if (isset($GLOBALS['language_stats'][$lang]) && $GLOBALS['language_stats'][$lang] < $cfg['TranslationWarningThreshold'] ) { trigger_error( 'You are using an incomplete translation, please help to make it better by [a@http://www.phpmyadmin.net/home_page/improve.php#translate@_blank]contributing[/a].', E_USER_NOTICE ); } } /** * prints list item for main page * * @param string $name displayed text * @param string $id id, used for css styles * @param string $url make item as link with $url as target * @param string $mysql_help_page display a link to MySQL's manual * @param string $target special target for $url * @param string $a_id id for the anchor, * used for jQuery to hook in functions * @param string $class class for the li element * @param string $a_class class for the anchor element * * @return void */ function PMA_printListItem($name, $id = null, $url = null, $mysql_help_page = null, $target = null, $a_id = null, $class = null, $a_class = null ) { echo '
'; if (null !== $url) { echo ''; } echo $name; if (null !== $url) { echo '' . "\n"; } if (null !== $mysql_help_page) { echo PMA_Util::showMySQLDocu('', $mysql_help_page); } echo '
'; } ?>
</code></pre>
<p>This issue is very similar to the one <a href="https://stackoverflow.com/questions/29266134/weird-error-in-phpmyadmin-it-is-installed-successfully-but-still-not-working">mentioned here</a>.</p>
<p>My concern is that I setup my config through puphpet so I am not sure if I follow along with the answer to that question if I will make it worse. Does anyone have any idea how I can fix this?</p>
<p>EDIT: I ended up following the steps in the answer I linked in my question and it all seems to have been fixed. Not sure if there is a way to mark this question as complete since there is technically no answer here. Please mark it as closed or answered.</p>
| 3 | 4,845 |
Ember routes not loaded in order
|
<p>I'm having an issue where the <code>beforeModel</code> (or <code>afterModel</code>) on my route isn't called <em>after</em> the application controller has been setup. This is an issue because I need some data from the application controller.</p>
<p>In another route this works as I'd expect (that the application controller is loaded prior to the route). The only difference is the one that works is an <code>Ember.ArrayController</code> and the one that doesn't is a standard <code>Ember.Controller</code>. I'm using <code>beforeModel</code> even though there isn't a model simply because I'm trying to transition away from it if a condition isn't meet.</p>
<p>If I change my non-working controller to an <code>Ember.ArrayController</code> and put in a pointless <code>model</code> call in the router then it still doesn't work.</p>
<p>The only other difference I can think of is that the one that isn't working is a nested controller defined by just a <code>route</code> and the working one isn't nested and is defined by <code>resource</code>.</p>
<pre><code>Router.map(function() {
this.resource("wizard", function() {
this.resource("wizard/schools", {path: "/schools"}, function() {
this.route("new"); // This one doesn't work
});
});
...
this.resource("schools", { path: "/schools" }); // This one does work
});
</code></pre>
<p>Any idea how I can ensure the application route/controller is loaded prior to my route?</p>
<p>I'm trying to do something along the lines of:</p>
<pre><code>beforeModel: function() {
var customerAccountPromise = this.controllerFor('application').get('customerAccount');
var self = this;
return customerAccountPromise.then(function(customerAccount) {
return self.get('store').find('school').then(function(schools) {
if (customerAccount.get('schoolLimit') <= schools.get('length')){
self.transitionTo('school', schools.get('firstObject'));
}
});
});
},
</code></pre>
<p>I'm currently running:</p>
<pre><code>DEBUG: Ember : 1.8.1
DEBUG: Ember Data : 1.0.0-beta.12
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery : 1.11.1
</code></pre>
<p><strong>Update:</strong> here is the code for the working route:</p>
<pre><code>import Ember from 'ember';
import AuthenticatedRoute from "./authenticated";
var SchoolsRoute = AuthenticatedRoute.extend({
model: function() {
return this.get('store').find('school');
},
afterModel: function(schools) {
Ember.Logger.log("SchoolsRoute - afterModel");
var customerAccountPromise = this.controllerFor('application').get('customerAccount');
var self = this;
return customerAccountPromise.then(function(customerAccount) {
if (customerAccount.get('schoolLimit') === 1){
self.transitionTo('school', schools.get('firstObject'));
}
});
},
});
</code></pre>
<p>export default SchoolsRoute;</p>
<p>The application controller is just aliasing the session controller.</p>
<pre><code>import Ember from 'ember';
var ApplicationController = Ember.Controller.extend({
needs: ['session'],
currentUser: Ember.computed.alias('controllers.session.currentUser'),
customerAccount: Ember.computed.alias('currentUser.customerAccount'),
...
});
export default ApplicationController;
</code></pre>
<p>The router for the application is pretty simple:</p>
<pre><code>import Ember from 'ember';
var ApplicationRoute = Ember.Route.extend({
setupController: function(controller, model) {
Ember.Logger.log("application setupController");
return this._super(controller, model);
},
...
});
export default ApplicationRoute;
</code></pre>
<p>The important part in <code>AuthenticatedRoute</code> is the <code>beforeModel</code>:</p>
<pre><code>beforeModel: function(transition) {
Ember.Logger.log("AuthenticatedRoute - beforeModel");
if (Ember.isEmpty(this.controllerFor('session').get('token'))) {
// set notification
return this.redirectToSignIn(transition);
}
},
</code></pre>
<p>There is no other "setting up" of the <code>SessionController</code>. It is simply called via the <code>controllerFor</code>. And on <code>init</code> it calls a <code>loadUser</code> method which immediately logs the message "SessionController - loadUser" and then does a <code>store.find</code> call and when that returns it logs a message about setting the user.</p>
<p>And the logs show that the application gets setup first:</p>
<pre><code>DEBUG: -------------------------------
DEBUG: Ember : 1.8.1
DEBUG: Ember Data : 1.0.0-beta.12
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery : 1.11.1
DEBUG: -------------------------------
AuthenticatedRoute - beforeModel
SessionController - loadUser
generated -> route:loading Object {fullName: "route:loading"}
application setupController
Rendering application with default view <school-app@view:toplevel::ember365> Object {fullName: "view:application"}
generated -> controller:loading Object {fullName: "controller:loading"}
Rendering loading with default view <school-app@view:default::ember386> Object {fullName: "view:loading"}
XHR finished loading: GET "http://0.0.0.0:4200/api/users?email=ryan%40ryanjm.com".
SessionController - set user
Ember Inspector Active
XHR finished loading: GET "http://0.0.0.0:4200/api/school".
SchoolsRoute - afterModel
</code></pre>
<p>Here is the session controller:</p>
<pre><code>import Ember from 'ember';
var SessionController = Ember.Controller.extend({
// called by updateHeaders
loadUser: function() {
Ember.Logger.log("SessionController - loadUser");
if (this.get('isSignedIn') && !this.get('currentUser')){
var self = this;
this.store.find('user', { email: this.get('email') }).then(function(users) {
Ember.Logger.log("SessionController - set user");
self.set('currentUser', users.get('firstObject'));
});
}
},
// if email/token change, update the headers
updateHeaders: function() {
if (this.get('isSignedIn')){
Ember.$.ajaxSetup({
headers: {
'X-User-Email': this.get('email'),
'X-User-Token': this.get('token')
}
});
this.loadUser();
}
}.observes('email', 'token').on('init'),
hasEmail: Ember.computed.notEmpty('email'),
hasToken: Ember.computed.notEmpty('token'),
isSignedIn: Ember.computed.and('hasEmail', 'hasToken'),
});
export default SessionController;
</code></pre>
<hr>
<p>Based on Kingpin2k's suggestion I looked at the case of it being a race condition and that was the issue.</p>
<p>Therefore I changed my SessionController to a normal object and then injected it into the application route so that I could return the <code>loadUser</code> function as a promise in the <code>beforeModel</code>.</p>
| 3 | 2,173 |
SWIG, Box2D, and C#
|
<p>What should be simple has turned into a convoluted mess of ugliness. So here's the story. I downloaded the awesome Box2D, took out the important c++ files and added an interface for SWIG. I then proceeded to create the Swig wrapper by using a makefile</p>
<pre><code>CC=g++
CFLAGS=-c -Wall -fPIC -I../
LDFLAGS=-shared -o box.dll
SOURCES=<OMITTED>
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=box2d.dll
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $@
.cpp.o:
$(CC) $(CFLAGS) $< -o $@
swig:
swig -csharp -c++ -outdir Wrapper Box2D.i
clean:
-rm Collision/*.o
-rm Collision/Shapes/*.o
-rm Common/*.o
-rm Dynamics/*.o
-rm Dynamics/Contacts/*.o
-rm Dynamics/Joints/*.o
-rm Rope/*.o
</code></pre>
<p>Pretty normal stuff, and it works fine (After fixing %includes and not #includes in the interface file). So I "make swig" in cygwin, no problems there (had to re-order includes so base classes came first). Then I loaded it up in VS.NET 2012, copying all the wrapper .cs files into the solution and moving the DLL over. This is where it gets nasty.</p>
<p>First time round, I believe it was mixed x86 and x64 that was causing great issue. I could instantly see that this was the problem and was in no way confused by the highly descriptive error message:</p>
<pre><code>System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
</code></pre>
<p>In my attempts to fix this, much of the Googling resolved that perhaps the calling convention was the culprate, so I changed the SWIG wrapper cpp file to export the functions into the dll as __cdecl rather than __stdcall, and updated the wrapper appropriately.</p>
<p>Anyway so I eventually fixed the x86/x64 mixing by making a new x86 build profile, and then upon calling any function in the dll, the program just hanged. So I decided to revert back to basics and simply compile with __stdcall, no wrapper mods, and just see if it would work. </p>
<p>It didn't. </p>
<p>Now it complains that it's missing entry points:</p>
<pre><code>{"Unable to find an entry point named 'SWIGRegisterExceptionCallbacks_box2d' in DLL 'box2d'.":""} System.Exception {System.EntryPointNotFoundException}
</code></pre>
<p>Upon dumping the exports of the DLL, the functions are correctly mangled according to __stdcall</p>
<pre><code>CSharp_b2_aabbMultiplier_get@0
...
SWIGRegisterStringCallback_box2d@4
SWIGRegisterExceptionCallbacks_box2d@44
</code></pre>
<p>etc. etc.</p>
<p>Now the C# wrapper end doesn't seem to find this a problem and goes straight ahead and ignores the mangling</p>
<pre><code>[DllImport("box2d", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_box2d")]
</code></pre>
<p>So I tried this out of desperation</p>
<pre><code>[DllImport("box2d", EntryPoint = "SWIGRegisterExceptionCallbacks_box2d", CallingConvention = CallingConvention.StdCall)]
</code></pre>
<p>Which was met with the same problem. The solution? Stick the mangled name in.</p>
<pre><code>[DllImport("box2d", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_box2d@44")]
</code></pre>
<p>... for all 1392 DllImport attributes. Not a solution. </p>
<p>I've tried compiling DLLs with both minGW and Cygwin, so I doubt that the way the DLLs are compiled is much of an issue.</p>
<p>Does anybody have any idea what I'm doing wrong?</p>
| 3 | 1,144 |
Layout Pushing Div Down
|
<p>I'm having an issue where my layout is pushing a div lower than expected. It's a fixed three row layout, but the second row seems to be pushed down. Fiddle and code below.</p>
<p><a href="http://jsfiddle.net/76wfg/" rel="nofollow">fiddle</a></p>
<p>CSS</p>
<pre><code>body, html{
margin:0px;
padding:0px;
width:100%;
height:100%;
background-color:black;
}
#wrapper{
width:100%;
height:100%;
padding:0px;
margin:0px;
background-color:black;
min-width:1050px;
}
#navbar{
width:100%;
height:30px;
background-color:#333333;
padding:0px;
margin:0px;
font-size:0px;
}
#content{
width:100%;
padding:0px;
margin:0px;
text-align:center;
}
#contentwrapper{
width:1000px;
padding:0px;
margin:0px;
text-align:center;
display:inline-block;
background-color:white;
border: 5px solid #333333;
}
#contentbottom{
text-align:center;
margin:0px;
padding:0px;
top:10px;
position:relative;
}
#contenttopimg{
float:left;
}
#contenttoptxt{
font-size:large;
font-weight:bold;
text-align:left;
}
.navtab{
height:20px;
background-color:#12c5f0;
font-weight:bold;
text-align:center;
display:inline-block;
padding:3px;
margin:0px;
border:2px solid black;
font-size:medium;
}
.navtab:hover{
background-color:#213655;
cursor:pointer;
}
.navtab a{
text-decoration:none;
color:black;
}
#contactwrapper{
padding:10px;
margin:0px;
background-color:#333333;
font-size:0px;
text-align:center;
}
.contacttitle{
font-weight:bold;
font-size:large;
text-align:left;
text-decoration:underline;
}
.contactdiv{
background-color:white;
border:2px solid black;
width:300px;
height:200px;
display:inline-block;
margin:3px;
}
.contactimgdiv{
width:300px;
height:200px;
display:inline-block;
margin:3px;
}
.contactimg{
height:200px;
}
</code></pre>
<p>HTML</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>End Slavery in Charlotte</title>
<link rel="stylesheet" type="text/css" href="./css/index.css" />
</head>
<body>
<div id="wrapper">
<div id="navbar">
<div id="homenav" class="navtab">
<a href="./index.html" >Home</a>
</div>
<div id="contactnav" class="navtab">
<a href="./contactus.html" >Contact Us</a>
</div>
</div>
<div id="content">
<div id="contentwrapper">
<div id="contactwrapper">
<div id="contacttop">
<div id="agencies" class="contactdiv">
<div id="agenciestitle" class="contacttitle">
Agencies
</div>
</div>
<div id="volunteers" class="contactdiv">
<div id="volunteerstitle" class="contacttitle">
Volunteers
</div>
</div>
<div id="groups" class="contactdiv">
<div id="groupstitle" class="contacttitle">
Groups
</div>
</div>
</div>
<div id="contactbottom">
<div id="contactimgleft" class="contactimgdiv">
<img src="./images/mainimg.jpg" class="contactimg" />
</div>
<div id="churches" class="contactdiv">
<div id="churchestitle" class="contacttitle">
Churches
</div>
</div>
<div id="contactimgright" class="contactimgdiv">
<img src="./images/mainimg.jpg" class="contactimg" />
</div>
</div>
<div id="contactbottom">
<div id="schools" class="contactdiv">
<div id="schoolstitle" class="contacttitle">
Schools
</div>
</div>
<div id="churches" class="contactdiv">
<div id="churchestitle" class="contacttitle">
Churches
</div>
</div>
<div id="societies" class="contactdiv">
<div id="societiestitle" class="contacttitle">
Societies
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
| 3 | 3,208 |
Render array's nested object values react
|
<p>Here is how my <code>savedLinksData</code> array prints in my console:</p>
<p><a href="https://i.stack.imgur.com/2EKer.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2EKer.png" alt="enter image description here" /></a></p>
<p>Here is my code that attempts to get the <code>linkType</code> value:</p>
<pre class="lang-js prettyprint-override"><code> {savedLinksData.map((saved) => {
return <h1>{saved.linkType}</h1>;
})}
</code></pre>
<p>What I'm doing wrong?</p>
<p>I think there may be something wrong with the way I stored the values in the array. It doesn't look like the value are inside of the array.</p>
<p>Picture of <code>console.log("----->", saved)</code></p>
<p><a href="https://i.stack.imgur.com/q4zr6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q4zr6.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/q4zr6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q4zr6.png" alt="enter image description here" /></a></p>
<pre class="lang-js prettyprint-override"><code>const [savedLinksData, setSavedLinksData] = useState([]);
// query for saved links data
useEffect(() => {
if (user) {
async function fetchData() {
const request = await db
.collection("users")
.doc(user)
.collection("saved")
.onSnapshot((snapshot) =>
setSavedLinks(
snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id }))
)
);
}
fetchData();
} else {
setSavedLinks([]);
}
}, [user]);
useEffect(() => {
if (savedLinks.length > 0) {
let newArray = [];
savedLinks.map((saved) => {
db.collection("users")
.doc(saved.savedUser)
.collection("links")
.doc(saved.savedLinkId)
.get()
.then(function (doc) {
if (doc.exists) {
// console.log("Document data:", doc.data());
newArray.push(doc.data());
// setSavedLinksData([...savedLinksData, doc.data()]);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function (error) {
console.log("Error getting document:", error);
});
});
setSavedLinksData(newArray);
}
}, [savedLinks]);
</code></pre>
| 3 | 1,198 |
$lookup in aggregation is very slow
|
<p>I am using <code>$lookup</code> to join two collections for counting, but <code>executionStats</code> shows that the query is very slow (500+ms per query for a single lookup). Here is the collection size:</p>
<pre><code>> db.visit.find({}).count()
8174
> db.links.find({}).count()
89
</code></pre>
<p>Here is the lookup strage for the aggregation:</p>
<pre><code>> db.visit.explain('executionStats').aggregate([{"$lookup": {from: "links", localField: "alias", foreignField: "alias", as: "url"}}])
</code></pre>
<p>results in:</p>
<pre><code>{
"stages": [
{
"$cursor": {
"queryPlanner": {
"plannerVersion": 1,
"namespace": "redir.visit",
"indexFilterSet": false,
"parsedQuery": {
},
"queryHash": "8B3D4AB8",
"planCacheKey": "8B3D4AB8",
"winningPlan": {
"stage": "COLLSCAN",
"direction": "forward"
},
"rejectedPlans": []
},
"executionStats": {
"executionSuccess": true,
"nReturned": 8174,
"executionTimeMillis": 642,
"totalKeysExamined": 0,
"totalDocsExamined": 8174,
"executionStages": {
"stage": "COLLSCAN",
"nReturned": 8174,
"executionTimeMillisEstimate": 0,
"works": 8176,
"advanced": 8174,
"needTime": 1,
"needYield": 0,
"saveState": 9,
"restoreState": 9,
"isEOF": 1,
"direction": "forward",
"docsExamined": 8174
}
}
},
"nReturned": NumberLong(8174),
"executionTimeMillisEstimate": NumberLong(7)
},
{
"$lookup": {
"from": "links",
"as": "url",
"localField": "alias",
"foreignField": "alias"
},
"nReturned": NumberLong(8174),
"executionTimeMillisEstimate": NumberLong(643)
}
]
}
</code></pre>
<p>Why and how to fix it?</p>
| 3 | 1,908 |
Using malloc and free in recursive file scanning function
|
<p>I am writing a function that takes in a file-path argument and scans through the directory structure and loads it into a tree. I'm using a recursive function I created called <code>scan_and_add_children(struct Node* root)</code> that takes in the root node. The idea is I loop through the files in a directory, add the current node to the tree, and, if it's a directory, I call my recursive function using the current node as the root to add all of that directories children as well. However, I keep getting a <code>malloc(): corrupted top size</code> error. I am wondering if the dynamically allocated memory in the <code>new_node_to_be_added</code> variable is being lost once I make my recursive call. I can't free the node before the call as it's being used in my recursive function. I am yet to add my function that free()'s the tree, however, I know this is not the issue as I set a break point at the end of main and my program breaks before it even gets out of the function. I'm not super experienced with dynamic memory managenemt so I am trying to use this exercise to get more practice. Can someone explain to me what's going wrong?</p>
<p>Here's my main program:</p>
<pre><code>#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include "linkedlist.h"
void scan_and_add_children(struct Node*);
int file_exists(char* path);
struct List* create_list(int level);
struct Node* create_node(int level, char* name);
int main(int argc, char** argv) {
if(argc != 2) {
printf("You must specify one path\n");
return(-1);
}
if(!file_exists(argv[1])) {
printf("Path not found or not valid\n");
return(-1);
}
struct stat filestat;
int level = 1;
struct Node* root = create_node(level, argv[1]);
struct List* rootList = create_list(1);
insert_tail(root, rootList);
//printf("%s\n", root->name);
stat(root->name, &filestat);
if(!S_ISDIR(filestat.st_mode)) { //if root node is a file
printf("Just a file\n");
return 1;
}
else {
scan_and_add_children(root);
}
}
void scan_and_add_children(struct Node* root) {
DIR* dir;
struct dirent* current;
struct stat filestat;
struct Node* new_node_to_be_added;
dir = opendir(root->name);
if(dir == NULL)
{
perror("Unable to read directory");
closedir(dir);
return;
}
while((current = readdir(dir))) {
if(current->d_name[0] == '.') { //skip files and directories that begin with a .
continue;
}
if(root->name[strlen(root->name)-1] != '/') { //add in / in order to make opendir functions work
root->name = strcat(root->name, "/");
}
char* rootCopy = strdup(root->name); //using root->name in strcat changes rootcopy and messes up absolute path
char* absolute_path = strcat(rootCopy, current->d_name);
//free(rootCopy);
printf("%s\n", absolute_path);
new_node_to_be_added = create_node(root->children->level, absolute_path); //create node and add to root->children
insert_tail(new_node_to_be_added, root->children);
stat(new_node_to_be_added->name, &filestat);
//print_list(root->children);
if(S_ISDIR(filestat.st_mode)) { //if it is a directory, scan and add its children, using new node to be added as root
scan_and_add_children(new_node_to_be_added);
}
}
free(new_node_to_be_added);
closedir(dir);
}
int file_exists(char* path) {
DIR* dir = opendir(path);
if(dir) {
closedir(dir);
return 1;
}
else return 0;
}
</code></pre>
<p>linkedlist.h:</p>
<pre><code>struct Node {
int id;
char* name;
struct Node* next;
struct List* children;
};
struct List {
int level;
int count;
struct Node* head;
struct Node* tail;
};
struct List* create_list(int level) {
struct List* list = malloc(sizeof(struct List));
if (list == NULL) {
fprintf (stderr, "%s: Couldn't create memory for the list; %s\n", "linkedlist", strerror (errno));
exit(-1);
}
list->head = NULL;
list->tail = NULL;
list->count = 0;
list->level = level;
return list;
}
struct Node* create_node(int level, char* name) {
struct Node* node = malloc(sizeof(struct Node));
if (node == NULL) {
fprintf(stderr, "%s: Couldn't create memory for the node; %s\n", "linkedlist", strerror (errno));
exit(-1);
}
node->name = strdup(name);
node->next = NULL;
node->children = create_list(level+1);
return node;
}
void insert_tail(struct Node* node, struct List* list) {
if(list->head == NULL) {
list->head = node;
list->tail = node;
list->count = 1;
node->id = list->count;
}
else {
list->tail->next = node;
list->tail = node;
list->count++;
node->id = list->count;
}
}
void print_list(struct List* list) {
struct Node* node = list->head;
while(node != NULL) {
if(node != list->head) {
printf("->");
}
printf("%d", node->id);
node = node->next;
}
}
void destroy_list(struct List* list) {
struct Node* node = list->head;
struct Node* tmp;
while(node != NULL) {
tmp = node;
node = node->next;
destroy_node(tmp);
}
free(list);
}
void destroy_node(struct Node* node) {
destroy_list(node->children);
free(node->name);
}
</code></pre>
<p>Output:</p>
<pre><code>-Surface-Book-2:/home/projects/project1$ ./dirtree /home/projects/
/home/projects/linked-li
/home/projects/project1
dirtree: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
-Surface-Book-2:/home/projects/project1$
</code></pre>
| 3 | 2,760 |
Create calculated field based on previous rows Oracle SQL
|
<p>I am trying to create a manually calculated column where I keep track of a current inventory.</p>
<p>Currently, I have a table that looks like this:</p>
<pre><code>| Group | Part | Operation Type | Transaction Amount |
|--------------|------|----------------|--------------------|
| Concrete | A | STOCK | 100 |
| Concrete | A | Buy | 25 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | B | STOCK | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | 150 |
| Construction | C | STOCK | 10 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | D | STOCK | 5 |
| Construction | D | Make | -5 |
</code></pre>
<p>The table is first ordered by <code>group</code> then by <code>part</code>, and then <code>STOCK</code> is always shown as the first value. The idea is to create a new manually calculated column, <code>curr_inventory</code>, that allows for us to keep track of current inventory and see if or when our inventory for a given part, for a given group, dips below 0.</p>
<p>Ideally, the end results would look like this:</p>
<pre><code>| Group | Part | Operation Type | Transaction Amount | New_Inventory_Column |
|:------------:|:----:|:--------------:|:------------------:|:--------------------:|
| Concrete | A | STOCK | 100 | 100 |
| Concrete | A | Buy | 25 | 125 |
| Concrete | A | Make | -10 | 115 |
| Concrete | A | Make | -10 | 105 |
| Concrete | A | Make | -10 | 95 |
| Concrete | A | Make | -10 | 85 |
| Concrete | A | Make | -10 | 75 |
| Concrete | B | STOCK | 10 | 10 |
| Concrete | B | Make | -10 | 0 |
| Concrete | B | Make | -10 | -10 |
| Concrete | B | Make | -10 | -20 |
| Concrete | B | Make | -10 | -30 |
| Concrete | B | Make | 150 | 120 |
| Construction | C | STOCK | 10 | 10 |
| Construction | C | Make | -1 | 9 |
| Construction | C | Make | -1 | 8 |
| Construction | C | Make | -1 | 7 |
| Construction | C | Make | -1 | 6 |
| Construction | D | STOCK | 5 | 5 |
| Construction | D | Make | -5 | 0 |
</code></pre>
<p>The end result would be a column that initiates when the part number has changed and the operation type is STOCK, and then begins to calculate (using the transaction amount) what the current inventory is.
I am not sure where to start on a SQL query that would allow for this. Intuitively, the pseudocode would look something like:</p>
<pre><code>for each row in table:
if operation_type == "stock":
curr_inv = stock.value
else:
curr_inv = previous_curr_inv + transaction_amount
</code></pre>
<p>However, I am not sure how to even begin writing SQL for this. I typically try to post what SQL I am working with but I don't even know where to begin. I have looked at various posts online, on SO, including posts <a href="https://stackoverflow.com/questions/37517940/sql-calculated-field-base-on-calculated-field">like this</a>, <a href="https://stackoverflow.com/questions/53268337/create-calculated-value-based-on-calculated-value-inside-previous-row">and this</a>, <a href="https://stackoverflow.com/questions/37776958/oracle-sql-calculate-value-using-previous-row">and this</a>, but I could not see how the selected answers could be used as a solution.</p>
| 3 | 2,731 |
history push does not match Route. Only changes the URL and defaults to catch all route instead
|
<p>I have React Router v5 with below code:</p>
<p>index.js</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
const muiTheme = createMuiTheme({
palette: {
primary: {
main: '#2196f3'
}
},
overrides: {
MUIDataTableSelectCell: {
fixedHeaderCommon: {
backgroundColor: 'transparent',
},
},
MuiTableCell: {
sizeSmall: {
padding: '6px 0 6px 16px'
}
},
MuiTableRow: {
hover: {
cursor: 'pointer'
}
}
}
});
ReactDOM.render(<MuiThemeProvider theme={muiTheme}><App /></MuiThemeProvider>, document.getElementById('root'));
serviceWorker.unregister();
</code></pre>
<p>App.js</p>
<pre><code>import {
// BrowserRouter as Router,
Switch,
Route,
Router,
// Link,
// useRouteMatch,
// useParams
} from "react-router-dom";
import history from 'history/browser';
import Dashboard from './common/components/Dashboard';
import Login from './common/components/Login';
import Test from './common/components/Test';
<Router history={history}>
<Switch>
<Route path="/test" component={Test} />
<Route path="/login" component={Login} />
<Route path="/" exact component={Dashboard} />
<Route component={Error404} />
</Switch>
</Router>
</code></pre>
<p>Login.js</p>
<pre><code>import { useHistory } from "react-router-dom";
export default function Login() {
let history = useHistory();
const classes = useStyles();
const storedToken = localStorage.getItem('token');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [remember, setRemember] = useState(false);
const [fetchError, setFetchError] = useState(null);
async function login(e) {
e.preventDefault();
try {
const data = await ApiClient.post(`/api/auth`, { email: email, password: password, remember: remember });
localStorage.setItem('token', data.token);
setFetchError(null);
history.push('/test');
} catch (err) {
if(err.response.status === 401) {
setFetchError('Unauthorized access, please login again.');
}
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Login
</Typography>
<form className={classes.form} noValidate onSubmit={login}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
onChange={(e) => setRemember(e.target.value)}
value={remember}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}
</code></pre>
<p>Whenever I submit with correct credentials I get 200 response code from the server with JWT token but after <code>history.push('/test');</code> on login function, I don't get the Route match with <code>/test</code> instead it goes to <code>Error404</code> catch all route.</p>
<p>How is this possible?</p>
| 3 | 2,527 |
xforms and getting a particular value from a list
|
<p>There is a small code that works with appache tomcat and chiba-3.0.0b2</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:xforms="http://www.w3.org/2002/xforms"
xmlns:events="http://www.w3.org/2001/xml-events">
<xhtml:head>
<xforms:model>
</code></pre>
<p>there is instance where to get a dynamic list</p>
<pre><code> <xforms:instance id="xs">
<xs>
<x kd="1" name="one"></x>
<x kd="2" name="two"></x>
<x kd="3" name="three"></x>
<!-- ... -->
</xs>
</xforms:instance>
</xforms:model>
</xhtml:head>
<xhtml:body>
</code></pre>
<p>There is a switch-case construction</p>
<pre><code><xforms:switch>
</code></pre>
<p>list case</p>
<pre><code><xforms:case id="list">
<xhtml:ul>
<xforms:itemset nodeset="instance('xs')/x">
<xhtml:li>
<xforms:trigger>
<xforms:toggle events:event="DOMActivate" case="onerec" />
<xforms:value ref="@kd" />
<xforms:label ref="@name" />
</xforms:trigger>
</xhtml:li>
</xforms:itemset>
</xhtml:ul>
</xforms:case>
</code></pre>
<p>one record case</p>
<pre><code><xforms:case id="onerec">
</code></pre>
<p>How to get a last submitted button value instead of '2' in formula [@kd=2] (i.e instead of [@kd=2] i like @kd='clicked trigger value')???</p>
<pre><code> <xforms:itemset nodeset="instance('xs')/x[@kd=2]">
There are name "<xforms:label ref="@name" />" and id "<xforms:value ref="@kd" />"
</xforms:itemset>
</code></pre>
<p>There is a back button</p>
<pre><code> <xforms:trigger>
</code></pre>
<p>opening the list case</p>
<pre><code> <xforms:toggle events:event="DOMActivate" case="list" />
<xforms:label>Back</xforms:label>
</xforms:trigger>
</xforms:case>
</xforms:switch>
</xhtml:body>
</xhtml:html>
</code></pre>
<p>Thank you</p>
| 3 | 1,281 |
Extending macro from 1 row to 56 rows. Application defined error
|
<p>Ihave never done Excel VBA macros.</p>
<p>The data I’m trying to get organized into a single column is in excel rows 22-78.</p>
<pre><code> 0 0.04 0.08 0.12 0.16 0.2 0.24 0.28 0.32 0.36 0.4 0.44 0.48 0.52 0.56 0.6 0.64 0.68 0.72 0.76 0.8 0.84 0.88 0.92 0.96 1 1.04 1.08 1.12 1.16 1.2 1.24 1.28 1.32 1.36 1.4 1.44 1.48 1.52 1.56 1.6 1.64 1.68 1.72 1.76 1.8 1.84 1.88 1.92 1.96 2 2.04 2.08 2.12 2.16 2.2 2.24 2.28 2.32 2.36 2.4 2.44 2.48 2.52 2.56 2.6 2.64 2.68 2.72 2.76 2.8 2.84 2.88 2.92 2.96 3 3.04 3.08 3.12 3.16 3.2 3.24 3.28 3.32 3.36 3.4 3.44 3.48 3.52 3.56 3.6 3.64 3.68 3.72 3.76 3.8 3.84 3.88 3.92 3.96 4 4.04 4.08 4.12 4.16 4.2 4.24 4.28 4.32 4.36 4.4 4.44 4.48 4.52 4.56 4.6 4.64 4.68 4.72 4.76 4.8 4.84 4.88 4.92 4.96 5 5.04 5.08 5.12 5.16 5.2 5.24 5.28 5.32 5.36 5.4 5.44 5.48 5.52 5.56 5.6 5.64 5.68 5.72 5.76 5.8 5.84 5.88 5.92 5.96 6 6.04 6.08 6.12 6.16 6.2 6.24 6.28 6.32 6.36 6.4 6.44 6.48 6.52 6.56 6.6 6.64 6.68 6.72 6.76 6.8 6.84 6.88 6.92 6.96 7 7.04 7.08 7.12 7.16 7.2 7.24 7.28 7.32 7.36 7.4 7.44 7.48 7.52 7.56 7.6 7.64 7.68 7.72 7.76 7.8 7.84 7.88 7.92 7.96 8 8.04 8.08 8.12 8.16 8.2 8.24 8.28 8.32 8.36 8.4 8.44 8.48 8.52 8.56 8.6 8.64 8.68 8.72 8.76 8.8 8.84 8.88 8.92 8.96 9 9.04 9.08 9.12 9.16 9.2 9.24 9.28 9.32 9.36 9.4 9.44 9.48 9.52 9.56 9.6 9.64 9.68 9.72 9.76 9.8 9.84 9.88 9.92 9.96 10 10.04 10.08 10.12 10.16 10.2 10.24 10.28 10.32 10.36 10.4 10.44 10.48 10.52 10.56 10.6 10.64 10.68 10.72 10.76 10.8 10.84 10.88 10.92 10.96 11 11.04 11.08 11.12 11.16 11.2 11.24 11.28 11.32 11.36 11.4 11.44 11.48 11.52 11.56 11.6 11.64 11.68 11.72 11.76 11.8 11.84 11.88 11.92 11.96 12 12.04 12.08 12.12 12.16 12.2 12.24 12.28 12.32 12.36 12.4 12.44 12.48 12.52 12.56 12.6 12.64 12.68 12.72 12.76 12.8 12.84 12.88 12.92 12.96 13 13.04 13.08 13.12 13.16 13.2 13.24 13.28 13.32 13.36 13.4 13.44 13.48 13.52 13.56 13.6 13.64 13.68 13.72 13.76 13.8 13.84 13.88 13.92 13.96 14 14.04 14.08 14.12 14.16 14.2 14.24 14.28 14.32 14.36 14.4 14.44 14.48 14.52 14.56 14.6 14.64 14.68 14.72 14.76 14.8 14.84 14.88 14.92 14.96 15 15.04 15.08 15.12 15.16 15.2 15.24 15.28 15.32
</code></pre>
<p>This is the data in one row. And such I have from row 22-78. the final files have a similar number of columns but many more rows.
I am not sure what would be a good way to organize this into a single column in excel </p>
<p>I got this working for 1 row.
here's the code </p>
<pre><code>Sub RowsToColumn()
Dim RN As Range
Dim RI As Range
Dim r As Long
Dim LR As Long
Application.ScreenUpdating = False
Columns(1).Insert
r = 0
LR = Range("A" & Rows.Count).End(xlUp).row
For Each RN In Range("A1:A" & LR)
r = r + 1
For Each RI In Range(RN, Range("XFD" & RN.row).End(xlToLeft))
r = r + 1
Cells(r, 1) = RI
RI.Clear
Next RI
Next RN
Columns("A:A").SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
End Sub
</code></pre>
<p>But to extend this for Rows A22-78</p>
<pre><code>Sub RowsToColumn_Second()
Dim RN As Range
Dim RI As Range
Dim r As Long
Dim LR As Long
Dim row As Range
Dim rng As Range
Dim cell As Range
Application.ScreenUpdating = False
Set rng = Range("A22:A78")
For Each row In rng.Rows
Columns(1, rng).Insert
r = 0
LR = Range("A" & Rows.Count).End(xlUp).row
LR = Range("A" & Rows.Count).End(xlUp).row
For Each RN In Range("A1:A" & LR)
r = r + 1
For Each RI In Range(RN, Range("XFD" & RN.row).End(xlToLeft))
r = r + 1
Cells(r, 1) = RI
RI.Clear
Next RI
Next RN
Next row
Columns("A:A").SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
End Sub
</code></pre>
<p>This is where it saysApplication defined error-1004. It doesn't like Columns(1, rng).Insert</p>
| 3 | 2,827 |
I need some help increasing the height of HTML canvas lines
|
<p>I am doing a project where the user selects what programming language they enjoy out of a radio box. It sets an object to the Local Storage and creates a bar graph and the bars go up depending on what choice the select. I'm having trouble though where if the user selects the language for the third time, it turns out what is in the image. I change the height each time and for some reason it also goes over the axis. I just want the height to change. I'm not super familiar with the canvas. Is there a way I could go about doing this? I just simply want the bar to start at the origin and go up, but not down.
Code below:</p>
<pre><code><!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<!DOCTYPE HTML>
<html>
<head>
<title>Extra Credit Challenge</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#entryArea{
border: 1px solid black;
width: 30%;
border-radius: 100px;
text-align: center;
margin: auto;
}
#myCanvas{
border-radius: 25px;
border: 1px;
}
#submitButton{
border-radius: 15px;
background-color:lightblue;
font-size: 25px;
width: 30%;
}
input{
font-size: 25px;
}
#resetButton{
border-radius: 15px;
background-color:lightblue;
font-size: 25px;
width: 30%;
}
</style>
</head>
<body onload="init()">
<canvas id="myCanvas" width="500" height="450" style="border:1px solid #000000;"></canvas>
<div id="entryArea">
<p style="font-size: 20px">What is your favorite programming language?</p>
<p><input name="language" type="radio" value="Web Design">Web Design</p>
<p><input name="language" type="radio" value="Java">Java</p>
<p><input name="language" type="radio" value="Python">Python</p>
<p><input name="language" type="radio" value="Other">Other</p>
<button id="submitButton">Submit</button><br><br>
<button id="resetButton">Reset</button>
</div>
<script>
function init(){
unCheckItems();
drawAxes();
walkThroughStorage();
document.getElementById("submitButton").addEventListener("click", setItemToStorage);
document.getElementById("resetButton").addEventListener("click", clearCanvas);
}
function walkThroughStorage(){
var ele = document.getElementById("entryArea").querySelectorAll("input");
var curTextStorage = localStorage.getItem("ClickedBoxes");
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
curTextStorage = JSON.parse(curTextStorage);
if(curTextStorage !== null){
for(let i = 0; i<ele.length; i++){
let height = (curTextStorage[ele[i].value] || 0) * 40;
if(ele[i].value === "Web Design"){
if(curTextStorage[ele[i].value] > 1){
ctx.rect(80, 310-(height/2), 30, height);
ctx.lineWidth = 1;
ctx.stroke();
}
if(curTextStorage[ele[i].value] === 1){
ctx.rect(80, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else if(ele[i].value === "Java"){
if(curTextStorage[ele[i].value] > 1){
ctx.rect(180, 310-(height/2), 30, height);
ctx.lineWidth = 1;
ctx.stroke();
}
if(curTextStorage[ele[i].value] === 1){
ctx.rect(180, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else if(ele[i].value === "Python"){
if(curTextStorage[ele[i].value] > 1){
ctx.rect(255, 310-(height/2), 30, height);
ctx.lineWidth = 1;
ctx.stroke();
}
if(curTextStorage[ele[i].value] === 1){
ctx.rect(255, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else{
if(curTextStorage[ele[i].value] > 1){
ctx.rect(335, 310-(height/2), 30, height);
ctx.lineWidth = 1;
ctx.stroke();
}
if(curTextStorage[ele[i].value] === 1){
ctx.rect(335, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
}
}
ctx.closePath();
}
function drawAxes(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
//draw x axis
ctx.moveTo(20,350);
ctx.lineTo(500,350);
ctx.lineWidth = 4;
ctx.stroke();
ctx.closePath();
//draw y axis
ctx.beginPath();
ctx.moveTo(40,400);
ctx.lineTo(40,0);
ctx.stroke();
ctx.closePath();
//draw names at the bottom
ctx.font = "15px Arial";
ctx.fillText("Web Design", 60,370);
ctx.fillText("Java", 180,370);
ctx.fillText("Python", 250,370);
ctx.fillText("Other", 330,370);
}
function unCheckItems(){
var ele = document.getElementById("entryArea").querySelectorAll("input");
for(let i = 0; i < ele.length; i++) {
if(ele[i].checked){
ele[i].checked = false;
}
}
}
function setItemToStorage(){
var savedClicks = localStorage.getItem("ClickedBoxes");
let clickDict = JSON.parse(savedClicks) || {};
var ele = document.getElementById("entryArea").querySelectorAll("input");
for(let i = 0; i < ele.length; i++){
if(ele[i].checked){
if(!clickDict[ele[i].value]){
clickDict[ele[i].value]=1;
}
else//the key of 1,2,3,4 or 5 (contents of curRandNum) exist in theDict so add one to its value
{
clickDict[ele[i].value] += 1;
}
}
localStorage.setItem("ClickedBoxes",JSON.stringify(clickDict));
}
drawBars();
}
function drawBars(){
var savedClicks = localStorage.getItem("ClickedBoxes");
savedClicks = JSON.parse(savedClicks);
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
var ele = document.getElementById("entryArea").querySelectorAll("input");
for(let i = 0; i < ele.length; i++) {
let height = (savedClicks[ele[i].value] || 0) * 40;
if(ele[i].checked){
if(ele[i].value === "Web Design"){
if(savedClicks[ele[i].value] > 1){
clearBar();
//ctx.clearRect(80, 300, 30, 40);
ctx.rect(80, 310-(height/2), 30, height);
ctx.lineWidth = 0;
ctx.stroke();
}
if(savedClicks[ele[i].value] === 1){
ctx.rect(80, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else if(ele[i].value === "Java"){
if(savedClicks[ele[i].value] > 1){
clearBar();
ctx.rect(180, 310-(height/2), 30, height);
ctx.lineWidth = 0;
ctx.stroke();
}
if(savedClicks[ele[i].value] === 1){
ctx.rect(180, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else if(ele[i].value === "Python"){
if(savedClicks[ele[i].value] > 1){
clearBar();
ctx.rect(255, 310-(height/2), 30, height);
ctx.lineWidth = 0;
ctx.stroke();
}
if(savedClicks[ele[i].value] === 1){
ctx.rect(255, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
else{
if(savedClicks[ele[i].value] > 1){
clearBar();
ctx.rect(335, 310-(height/2), 30, height);
ctx.lineWidth = 0;
ctx.stroke();
}
if(savedClicks[ele[i].value] === 1){
ctx.rect(335, 310, 30, 40);
ctx.lineWidth = 1;
ctx.stroke();
}
}
}
}
ctx.closePath();
}
function clearBar(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
init();
}
function clearCanvas(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
localStorage.clear();
init();
}
</script>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/CqYn5.png" rel="nofollow noreferrer">Here is the image photo</a>
Thanks in advance!</p>
| 3 | 8,268 |
how to customize remote validation like a normal jquery ajax?
|
<p>Is there a way we can customize remote validation like a normal jquery ajax?</p>
<pre><code>$('#banner').bootstrapValidator({
framework: 'bootstrap',
fields: {
bannerType: {
icon: false,
validators: {
notEmpty: {
message: 'Banner type is required'
}
}
},
bannerTitle: {
icon: false,
validators: {
notEmpty: {
message: 'Banner title is required'
}
}
},
bfromDate: {
verbose: true,
validators: {
notEmpty: {
message: 'From date is required'
},
date: {
format: 'MM/DD/YYYY',
message: 'The value is not a valid date'
},
remote: {
url: '/assets/cfc/exchange/exchangeintra.cfc?method=checkAvailabilityofDates',
type: 'POST',
dataType:'json',
data: function(validator, $field, value) {
return {
selectedDate: validator.getFieldElements('bfromDate').val(),
bannerId: validator.getFieldElements('bannerId').val(),
};
},
}
}
},
btoDate: {
verbose: true,
validators: {
notEmpty: {
message: 'To date is required'
},
date: {
format: 'MM/DD/YYYY',
message: 'The value is not a valid date'
},
remote: {
url: '/assets/cfc/exchange/exchangeintra.cfc?method=checkAvailabilityofDates',
type: 'POST',
dataType:'json',
data: function(validator, $field, value) {
return {
selectedDate: validator.getFieldElements('btoDate').val(),
bannerId: validator.getFieldElements('bannerId').val(),
};
},
}
}
},
authorImage: {
validators: {
notEmpty: {
message: 'Banner image is required'
},
file: {
extension: 'jpeg,jpg,png',
type: 'image/jpeg,image/png',
message: 'The selected file is not valid'
}
}
},
bannerLink: {
icon: false,
validators: {
notEmpty: {
message: 'Banner link is required'
}
}
}
}
});
</code></pre>
<p>When remote validation success than do any other things,if failed than do another things.</p>
<p>I have got the following link: <a href="http://formvalidation.io/examples/using-data-returned-validator/" rel="nofollow">http://formvalidation.io/examples/using-data-returned-validator/</a></p>
<p>But it is work,only if i am using formvalidation but here i am using bootstrapValidator.so is there any way to do the same like formvalidation.</p>
| 3 | 2,300 |
jQuery client side password verification
|
<p>first of all I'd like to say <strong>I realise</strong> it's not a secure method.
This is only for training purpose.</p>
<p>The algorhitm should be:</p>
<ol>
<li>click on a div with id="login-bg"</li>
<li>app displays the banner</li>
<li>provide the code</li>
<li>if the code's ok set cookie and fade out the banner</li>
<li>if the code's not ok the div shakes (still remaining on the screen)</li>
<li>if you don't want to provide the code press 'cancel' and fade out the banner</li>
</ol>
<p>Set cookie function (it works fine):</p>
<pre><code><?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<script type="text/javascript">
function SetPwd(c_name,value,expiredays){
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+";path=/"+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
</script>
<?php } ?>
</code></pre>
<p><strong>And here must be the problem with jQuery:</strong></p>
<pre><code><?php
if(!isset($_COOKIE['is_logged']))
{ ?>
<div id="login-bg">
<div class="content">
<h2>Provide the code!</h2>
<form id="check-form" method="post" action="">
<input type="password" name="code" placeholder="code" id="code" />
<input type="submit" value="Submit" id="enjoy"/>
</form>
<h3>And enjoy free access!</h3>
<a id="cancel">Cancel</a>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
if( document.cookie.indexOf("is_logged") ===-1 ){
$('#video').click(function(){
$("#login-bg").fadeIn('slow');
});
$('#cancel').click(function(){
$('#login-bg').fadeOut('slow');
//window.location = "<?php echo $this->baseUrl; ?>/index";
});
}
$("#submit").click(function (){
var value = $('#code').val();
var pass = 'test';
if( value == test ){
SetCookie('is_logged','is_logged',365*10)
$("#login-bg").remove();
}
else {
$('#login-bg').effect( "shake" );
}
});
});
</script>
<?php } ?>
</code></pre>
<p>In my opinion the value '#code' id not passed to jQuery from the form.<br>
But I may be wrong.</p>
<p>Do you have any ideas. Could you make it work?<br>
Thanks for your help.</p>
| 3 | 1,494 |
Use neural netword to fit a reduced boolean function, but found the super-params not as expected
|
<p>This is the boolean function I try to fit.
[boolean function description][1]</p>
<p>Theoretically we need a neural network with 1 hidden layer which has 3 neurons at least.<br />
And that's actually how I built the neural network in Pytorch.<br />
However, despite the prediction of NN usually correct, the parameters (I mean the weights and bias) not as expected.<br />
I expect the parameters to be like this way(A perceptron operation is equivalent to a Boolean gate):<br />
[perceptron equivalent to a boolean gate][2]</p>
<p>Here the key code:</p>
<pre><code>class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.linear_relu_stack = nn.Sequential(
nn.Linear(4, 3),
nn.ReLU(),
nn.Linear(3, 1),
)
def forward(self, x):
logits = self.linear_relu_stack(x)
return logits
base_lr = 0.001
optimizer = torch.optim.Adam(model.parameters(), base_lr)
criterion = nn.MSELoss().to(device)
</code></pre>
<p>Here is the key output:</p>
<p>First, the prediction not so bad, The categories are correct, but some of the numbers are not precise enough</p>
<pre><code> w x y z pred
0 0 0 0 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
1 0 0 0 1 [tensor(0.2459, grad_fn=<UnbindBackward0>)]
2 0 0 1 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
3 0 0 1 1 [tensor(0.0040, grad_fn=<UnbindBackward0>)]
4 0 1 0 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
5 0 1 0 1 [tensor(0.7707, grad_fn=<UnbindBackward0>)]
6 0 1 1 0 [tensor(-0.0015, grad_fn=<UnbindBackward0>)]
7 0 1 1 1 [tensor(-0.0025, grad_fn=<UnbindBackward0>)]
8 1 0 0 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
9 1 0 0 1 [tensor(-0.2525, grad_fn=<UnbindBackward0>)]
10 1 0 1 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
11 1 0 1 1 [tensor(-0.0077, grad_fn=<UnbindBackward0>)]
12 1 1 0 0 [tensor(0.9992, grad_fn=<UnbindBackward0>)]
13 1 1 0 1 [tensor(0.2722, grad_fn=<UnbindBackward0>)]
14 1 1 1 0 [tensor(-0.0066, grad_fn=<UnbindBackward0>)]
15 1 1 1 1 [tensor(0.0033, grad_fn=<UnbindBackward0>)]
</code></pre>
<p>Second, the parameters are not as expected.</p>
<pre><code> linear_relu_stack.0.weight tensor([[-0.3637, 0.3838, 0.7624, 0.3661],
[ 0.2857, 0.5719, 0.5721, -0.5846],
[ 0.4782, -0.5035, -0.2349, 1.2070]])
linear_relu_stack.0.bias tensor([-0.7657, -0.8599, -0.4842])
linear_relu_stack.2.weight tensor([[-1.3418, -1.7255, -1.0422]])
linear_relu_stack.2.bias tensor([0.9992])
</code></pre>
<p>My question is why the NN doesn't convege to my expected position?<br />
What' the problem?
[1]: <a href="https://i.stack.imgur.com/WqaXi.png" rel="nofollow noreferrer">https://i.stack.imgur.com/WqaXi.png</a>
[2]: <a href="https://i.stack.imgur.com/Z9cQb.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Z9cQb.png</a></p>
| 3 | 1,447 |
Issues Parsing Multi Nested Childs in XML using lxml
|
<p>Im having issues parsing out each child node within an xml file. The number of nodes can change per Instrument_Root. For instance, Instrument_Watch is NULL here, but will be populated in other instances after this. My goal is to have each child node parsed individually (Instrument_Ratings, Instrument_Attribute_Ratings, Instrument_Organization, Instrument_Supports, etc.)</p>
<p>I tried doing the following, but it just returned the first intance repeatedly - there are 3700 Instrument_Root in the file, and Instrument_Rating for this one Instrument_Root was repeated 3700 times. I also ran into errors with etree due to the namespace. </p>
<pre><code>from lxml import objectify
xml = objectify.parse(file)
root = xml.getroot()
tree1 = []
tree2 = []
tree3 = []
tree4 = []
for children in range(len(root.getchildren())):
tree1.append([child.text for child in root.getchildren()[children].iterchildren()])
for children2 in root.Instrument_Root.Instrument_Ratings.Instrument_Rating.getchildren():
tree2.append([child2.text for child2 in root.Instrument_Root.Instrument_Ratings.Instrument_Rating.getchildren()])
for children3 in root.Instrument_Root.Instrument_Ratings.Instrument_Rating.Instrument_Rating_Attributes.Instrument_Rating_Attribute.getchildren():
tree3.append([child3.text for child3 in root.Instrument_Root.Instrument_Ratings.Instrument_Rating.Instrument_Rating_Attributes.Instrument_Rating_Attribute.getchildren()])
for children4 in root.Instrument_Root.Instrument_Organizations.Instrument_Organization.getchildren():
tree4.append([child4.text for child4 in root.Instrument_Root.Instrument_Organizations.Instrument_Organization.getchildren()])
</code></pre>
<p>XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Instrument_Roots xmlns="http://www.XXXXX.com" xmlns:xsi="http://www.XXXXXXX.XMLSchema-instance" file_type="Baseline" frequency="Hourly-12" generation_time="2020-04-06T12:00:00Z">
<Instrument_Root>
<Instrument_ID>831295951</Instrument_ID>
<Deal_number>831275547</Deal_number>
<Class_Code>18705</Class_Code>
<Class_Text>Pass-Through</Class_Text>
<Class_Short_Description>PAS</Class_Short_Description>
<Dated_Date>2020-03-21T00:00:00</Dated_Date>
<ISO_Currency_Code>AUD</ISO_Currency_Code>
<Currency_Multiple_Indicator>N</Currency_Multiple_Indicator>
<Maturity_Date>2051-03-21T00:00:00</Maturity_Date>
<Maturity_Year>2051</Maturity_Year>
<Sale_Date>2020-03-21T00:00:00</Sale_Date>
<Face_Amount_USD>7.2534316791</Face_Amount_USD>
<Credit_Linked_Indicator>N</Credit_Linked_Indicator>
<Takedown_Indicator>N</Takedown_Indicator>
<Security_Description>Class B</Security_Description>
<Instrument_Type_Code>24657</Instrument_Type_Code>
<Instrument_Type_Text>PASS-THRU CTFS</Instrument_Type_Text>
<Private_Placement_Code>24922</Private_Placement_Code>
<Private_Placement_Text>Not Applicable</Private_Placement_Text>
<Coupon_Type_Code>26</Coupon_Type_Code>
<Coupon_Type_Text>Floating</Coupon_Type_Text>
<Coupon_Type_Short_Description>FLT</Coupon_Type_Short_Description>
<Coupon_Frequency_Code>16</Coupon_Frequency_Code>
<Coupon_Frequency_Text>Monthly</Coupon_Frequency_Text>
<Coupon_Frequency_Short_Description>MON</Coupon_Frequency_Short_Description>
<Coupon_Rate xsi:nil="true"/>
<Instrument_Description xsi:nil="true"/>
<Product_Line_Description>MBS - Prime</Product_Line_Description>
<Series_Class_Text>Class B</Series_Class_Text>
<Market_Description>AUSTRALIA</Market_Description>
<Face_Amount>11.2500000000</Face_Amount>
<Structured_Finance_Indicator>Y</Structured_Finance_Indicator>
<Structured_Finance_Sequence_Number>3</Structured_Finance_Sequence_Number>
<Instrument_Ratings>
<Instrument_Rating>
<Instrument_ID>831295951</Instrument_ID>
<Rating_Class_Number>37203</Rating_Class_Number>
<Rating_Date>2020-03-02T01:30:03</Rating_Date>
<XXXX_Rating_ID>831295958</XXXX_Rating_ID>
<Rating_Level>I</Rating_Level>
<Rating_Class_Text>Senior Secured</Rating_Class_Text>
<Security_Class_Code>18705</Security_Class_Code>
<Security_Class_Text>Pass-Through</Security_Class_Text>
<Security_Class_Short_Description>PAS</Security_Class_Short_Description>
<Duration_Code>25636</Duration_Code>
<Duration_Text>Long-Term Debt Rating</Duration_Text>
<Duration_Short_Description>LT</Duration_Short_Description>
<Seniority_Code>18743</Seniority_Code>
<Seniority_Text>Senior Secured</Seniority_Text>
<Seniority_Short_Description>SS</Seniority_Short_Description>
<Evaluation_Type_Code>25648</Evaluation_Type_Code>
<Evaluation_Type_Text>Credit Risk</Evaluation_Type_Text>
<Shadow_Code>5734</Shadow_Code>
<Shadow_Text>Enhanced</Shadow_Text>
<Shadow_Short_Description>ENH</Shadow_Short_Description>
<Rating_Subclass_Code xsi:nil="true"/>
<Rating_Subclass_Text xsi:nil="true"/>
<Currency_Capd_Code>19142</Currency_Capd_Code>
<Currency_Capd_Text>Local Currency</Currency_Capd_Text>
<Rating_Text>NR</Rating_Text>
<Credit_Grade xsi:nil="true"/>
<Rating_Rank>0</Rating_Rank>
<Rating_Direction_Code>19102</Rating_Direction_Code>
<Rating_Direction_Text>DECISION NOT TO RATE</Rating_Direction_Text>
<Rating_Direction_Short_Description>NR</Rating_Direction_Short_Description>
<Rating_Type_Code>534</Rating_Type_Code>
<Rating_Type_Text>Long-Term Debt Rating</Rating_Type_Text>
<Rating_Type_Short_Description>LT</Rating_Type_Short_Description>
<Rating_Enhancement_Level>ENH</Rating_Enhancement_Level>
<Rating_Local_Date>2020-03-02T17:30:03</Rating_Local_Date>
<Rating_Termination_Date xsi:nil="true"/>
<Rating_Termination_Local_Date xsi:nil="true"/>
<Rating_Reason_Code>25530</Rating_Reason_Code>
<Rating_Reason_Text>DECISION NOT TO RATE</Rating_Reason_Text>
<Rating_Currency_Code>20525</Rating_Currency_Code>
<Rating_Currency_Text>Australian Dollar</Rating_Currency_Text>
<Rating_Currency_ISO_Code>AUD</Rating_Currency_ISO_Code>
<Rating_Monitor_Indicator>1</Rating_Monitor_Indicator>
<Initial_Rating_Indicator>Y</Initial_Rating_Indicator>
<Instrument_Watchlist xsi:nil="true"/>
<Instrument_Rating_Attributes>
</Instrument_Rating_Attributes>
</Instrument_Rating>
</Instrument_Ratings>
<Instrument_Supports xsi:nil="true"/>
<Instrument_Organizations>
<Instrument_Organization>
<Organization_ID>88100</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>5156484</Organization_Role_Code>
<Organization_Role_Text>Issuer Account Bank</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>435700</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600045234</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>25017</Organization_Role_Code>
<Organization_Role_Text>Seller</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600045234</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>25020</Organization_Role_Code>
<Organization_Role_Text>Servicer</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>530750</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>24998</Organization_Role_Code>
<Organization_Role_Text>Arranger</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>540500</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>714325</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>192835</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600020914</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>831295948</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>129</Organization_Role_Code>
<Organization_Role_Text>Issuer</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600018753</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>140</Organization_Role_Code>
<Organization_Role_Text>Trustee</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600045234</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>25002</Organization_Role_Code>
<Organization_Role_Text>Custodian</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>806942842</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>140</Organization_Role_Code>
<Organization_Role_Text>Trustee</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>820688318</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>5155837</Organization_Role_Code>
<Organization_Role_Text>Cash Manager</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>530750</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>141</Organization_Role_Code>
<Organization_Role_Text>Underwriter</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
<Instrument_Organization>
<Organization_ID>600045234</Organization_ID>
<Instrument_ID>831295951</Instrument_ID>
<Organization_Role_Code>25012</Organization_Role_Code>
<Organization_Role_Text>Originator</Organization_Role_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Organization>
</Instrument_Organizations>
<Instrument_Identifiers xsi:nil="true"/>
<Instrument_Attributes>
<Instrument_Attribute>
<Instrument_ID>831295951</Instrument_ID>
<Rating_Attribute_Type_Code>5156438</Rating_Attribute_Type_Code>
<Rating_Attribute_Type_Text>SF Indicator</Rating_Attribute_Type_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
<Rating_Attribute_Code>5156439</Rating_Attribute_Code>
<Rating_Attribute_Text>(sf)</Rating_Attribute_Text>
</Instrument_Attribute>
<Instrument_Attribute>
<Instrument_ID>831295951</Instrument_ID>
<Rating_Attribute_Type_Code>5168187</Rating_Attribute_Type_Code>
<Rating_Attribute_Type_Text>SEC Exempt</Rating_Attribute_Type_Text>
<Effective_Date>2020-03-02T01:30:03</Effective_Date>
<Termination_Date xsi:nil="true"/>
<Rating_Attribute_Code>5168185</Rating_Attribute_Code>
<Rating_Attribute_Text>Exempt</Rating_Attribute_Text>
</Instrument_Attribute>
</Instrument_Attributes>
<Instrument_Markets>
<Instrument_Market>
<Instrument_ID>831295951</Instrument_ID>
<Domain_Number>75300</Domain_Number>
<Effective_Date>2020-03-21T00:00:00</Effective_Date>
<Termination_Date xsi:nil="true"/>
</Instrument_Market>
</Instrument_Markets>
</Instrument_Root>
</Instrument_Roots>
</code></pre>
<p>Any ideas on how to attack this would be greatly appreciated. Thanks. </p>
| 3 | 10,069 |
Unable to correcty call a void function in Java to output to the console
|
<p>I have the following class written in the Employee.java script:</p>
<pre><code>public class Employee {
//***************************************************************
//
// Developer: Erin
//
// Program #: 3
//
// File Name: Program3.java
//
// Course: Object-Oriented Programming - Java
//
// Due Date:
//
// Instructor: Prof. Fred
//
// Chapter: 3
//
// Description:
// Program creates an Employee class that includes three (3) private instances:
// 1) first name (String)
// 2) last name (String)
// 3) monthly salary (double)
// Program provides:
// a) a constructor that initializes instance variables
// b) set and get methods for each instance variable
// c) test app named EmployeeTest that demonstrates Employee class capabilities
// d) two (2) Employee objs, from which obj's yearly salary is displayed
// e) display of 20% raise for each Employee;s yearly salary
//
//***************************************************************
private String _first_name;
private String _last_name;
private double _monthly_salary;
public Employee(String first_name, String last_name, double monthlySalary)
{
setFirstName(first_name);
setLastName(last_name);
setMonthlySalary(monthlySalary);
}
public String getFirstName()
{
return _first_name;
}
public void setFirstName(String first_name)
{
_first_name = first_name;
}
public String getLastName()
{
return _last_name;
}
public void setLastName(String lastName)
{
_last_name =lastName;
}
public double getMonthlySalary()
{
return _monthly_salary;
}
public void setMonthlySalary(double monthlySalary)
{
if(monthlySalary < 0.0)
{
monthlySalary = 0.0;
}
_monthly_salary = monthlySalary;
}
//***************************************************************
//
// Method: developerInfo
//
// Description: The developer information method of the program
//
// Parameters: None
//
// Returns: N/A
//
//**************************************************************
public void developerInfo()
{
System.out.println("Name: Erin");
System.out.println("Course: Object-Oriented Programming");
System.out.println("Program: Three \n");
}
}
</code></pre>
<p>With the corresponding test class written in a separate script called EmployeeTest.java:</p>
<pre><code>public class EmployeeTest {
public static void main(String[] args) {
**developerInfo();**
Employee employee1 = new Employee("John", "Doe", 2875.00);
Employee employee2 = new Employee("Jane", "Doe", 3150.00);
System.out.printf("%s %n", "Before 20% raise:");
System.out.printf( "Employee 1: %s %s; Yearly Salary: $%.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: $%.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
employee1.setMonthlySalary(employee1.getMonthlySalary() * 1.2);
employee2.setMonthlySalary(employee2.getMonthlySalary() * 1.2);
System.out.printf("%s %n", "After 20% raise:");
System.out.printf( "Employee 1: %s %s; Yearly Salary: $%.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: $%.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
}
}
</code></pre>
<p>I cannot figure out how to call the developerInfo function in order get that to print to the console. Expected output is:</p>
<pre><code>Name: Erin
Course: Object-Oriented Programming
Program: Three
Before 20% raise:
Employee 1: John Doe; Yearly Salary: $34500.00
Employee 2: Jane Doe; Yearly Salary: $37800.00
After 20% raise:
Employee 1: John Doe; Yearly Salary: $41400.00
Employee 2: Jane Doe; Yearly Salary: $45360.00
</code></pre>
<p>Any insight would be so appreciated! Thank you!</p>
| 3 | 2,324 |
Phonegap file transfer using ashx http handler - files are not found on server
|
<p>I'm trying to upload an image to a remote server using Phonegap's (3.4.0) file transfer and an ashx http handler. I'm using eclipse and running the app on a galaxy s3 device.
here's my code:</p>
<p>js:</p>
<pre><code>function updateUserImage(userId,imageURI) {
//imageURI is in the format of file:///...
alert("in update()");
window.resolveLocalFileSystemURL(imageURI, onResolveSuccess, fail);
}
function onResolveSuccess(fileEntry) {
var options = new FileUploadOptions(); // PhoneGap object to allow server upload
options.fileKey = "file";
options.fileName = "1000.jpg";
options.mimeType = "image/jpeg"; // file type
options.chunkedMode = false;
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.headers = {
Connection: "close"
};
var ft = new FileTransfer();
alert("resolve success");
alert(fileEntry.toURL());
ft.upload(fileEntry.toURL(), encodeURI("http://www.xxxx.com/ReturnValue.ashx"), win, fail, options, true); // Upload
}
function win(r) {
alert("win");
alert(r.response);
}
</code></pre>
<p>ashx:</p>
<pre><code><%@ WebHandler Language="C#" Class="ReturnValue" %>
using System;
using System.Web;
public class ReturnValue : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Write(context.Request.Files.Count);
}
public bool IsReusable
{
get
{
return false;
}
}
}
</code></pre>
<p>logcat:</p>
<pre><code>05-14 17:56:01.834: V/webview(2125): singleCursorHandlerTouchEvent -getEditableSupport FASLE
05-14 17:56:02.224: W/PluginManager(2125): THREAD WARNING: exec() call to Camera.takePicture blocked the main thread for 56ms. Plugin should use CordovaInterface.getThreadPool().
05-14 17:56:02.224: D/CordovaActivity(2125): Paused the application!
05-14 17:56:02.224: D/CordovaWebView(2125): Handle the pause
05-14 17:56:02.819: W/IInputConnectionWrapper(2125): showStatusIcon on inactive InputConnection
05-14 17:56:08.274: D/CordovaActivity(2125): Incoming Result
05-14 17:56:08.274: D/CordovaActivity(2125): Request code = 34
05-14 17:56:08.274: D/CordovaActivity(2125): We have a callback to send this result to
05-14 17:56:08.314: D/dalvikvm(2125): GC_FOR_ALLOC freed 841K, 11% free 12366K/13831K, paused 16ms, total 24ms
05-14 17:56:08.379: I/dalvikvm-heap(2125): Grow heap (frag case) to 43.056MB for 31961104-byte allocation
05-14 17:56:08.394: D/dalvikvm(2125): GC_FOR_ALLOC freed 6K, 4% free 43571K/45063K, paused 14ms, total 14ms
05-14 17:56:08.394: W/CursorWrapperInner(2125): Cursor finalized without prior close()
05-14 17:56:08.409: D/dalvikvm(2125): GC_CONCURRENT freed <1K, 4% free 43571K/45063K, paused 2ms+3ms, total 16ms
05-14 17:56:10.139: D/dalvikvm(2125): WAIT_FOR_CONCURRENT_GC blocked 0ms
05-14 17:56:10.169: D/dalvikvm(2125): GC_EXPLICIT freed 31267K, 73% free 12321K/45063K, paused 3ms+4ms, total 30ms
05-14 17:56:10.169: E/System(2125): Uncaught exception thrown by finalizer
05-14 17:56:10.174: E/System(2125): java.io.IOException: close failed: EIO (I/O error)
05-14 17:56:10.174: E/System(2125): at libcore.io.IoUtils.close(IoUtils.java:41)
05-14 17:56:10.174: E/System(2125): at java.io.FileInputStream.close(FileInputStream.java:121)
05-14 17:56:10.174: E/System(2125): at java.io.FileInputStream.finalize(FileInputStream.java:142)
05-14 17:56:10.174: E/System(2125): at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:186)
05-14 17:56:10.174: E/System(2125): at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:169)
05-14 17:56:10.174: E/System(2125): at java.lang.Thread.run(Thread.java:856)
05-14 17:56:10.174: E/System(2125): Caused by: libcore.io.ErrnoException: close failed: EIO (I/O error)
05-14 17:56:10.174: E/System(2125): at libcore.io.Posix.close(Native Method)
05-14 17:56:10.174: E/System(2125): at libcore.io.BlockGuardOs.close(BlockGuardOs.java:75)
05-14 17:56:10.174: E/System(2125): at libcore.io.IoUtils.close(IoUtils.java:38)
05-14 17:56:10.174: E/System(2125): ... 5 more
05-14 17:56:10.174: W/CursorWrapperInner(2125): Cursor finalized without prior close()
05-14 17:56:10.174: I/CordovaLog(2125): Changing log level to DEBUG(3)
05-14 17:56:10.179: D/Whitelist(2125): Unlimited access to network resources
05-14 17:56:10.179: D/CordovaActivity(2125): Resuming the App
05-14 17:56:10.179: D/CordovaActivity(2125): CB-3064: The errorUrl is null
05-14 17:56:10.234: D/CordovaLog(2125): file:///android_asset/www/index.html: Line 23 : file:///storage/sdcard0/Android/data/com.phonegap.helloworld/cache/1400079368295.jpg
05-14 17:56:10.234: I/Web Console(2125): file:///storage/sdcard0/Android/data/com.phonegap.helloworld/cache/1400079368295.jpg:23
05-14 17:56:10.289: D/dalvikvm(2125): GC_CONCURRENT freed 42K, 72% free 12737K/45063K, paused 2ms+13ms, total 28ms
05-14 17:56:10.304: D/SoftKeyboardDetect(2125): Ignore this event
05-14 17:56:10.454: D/SoftKeyboardDetect(2125): Ignore this event
05-14 17:56:16.739: D/FileTransfer(2125): upload file:///storage/sdcard0/Android/data/com.phonegap.helloworld/cache/1400079368295.jpg to http://www.xxxx.com/ReturnValue.ashx
05-14 17:56:16.739: D/FileTransfer(2125): fileKey: file
05-14 17:56:16.739: D/FileTransfer(2125): fileName: 1000.jpg
05-14 17:56:16.739: D/FileTransfer(2125): mimeType: image/jpeg
05-14 17:56:16.739: D/FileTransfer(2125): params: {"value1":"test","value2":"param"}
05-14 17:56:16.739: D/FileTransfer(2125): trustEveryone: true
05-14 17:56:16.739: D/FileTransfer(2125): chunkedMode: false
05-14 17:56:16.739: D/FileTransfer(2125): headers: {"Connection":"close"}
05-14 17:56:16.739: D/FileTransfer(2125): objectId: 1
05-14 17:56:16.739: D/FileTransfer(2125): httpMethod: POST
05-14 17:56:16.764: D/FileTransfer(2125): Content Length: 358920
05-14 17:56:34.384: D/dalvikvm(2125): GC_CONCURRENT freed 150K, 72% free 12974K/45063K, paused 8ms+5ms, total 47ms
05-14 17:56:58.089: D/FileTransfer(2125): Uploaded 114920 of 358920 bytes
05-14 17:57:15.299: D/FileTransfer(2125): Uploaded 229608 of 358920 bytes
05-14 17:57:17.069: D/FileTransfer(2125): Uploaded 344296 of 358920 bytes
05-14 17:57:17.704: D/FileTransfer(2125): Sent 358920 of 358920
05-14 17:57:22.229: D/FileTransfer(2125): response code: 200
05-14 17:57:22.234: D/FileTransfer(2125): response headers: {null=[HTTP/1.1 200 OK], Cache-Control=[private], Connection=[close], Content-Type=[text/html; charset=utf-8], Date=[Wed, 14 May 2014 14:57:33 GMT], OkHttp-Received-Millis=[1400079442236], OkHttp-Response-Source=[NETWORK 200], OkHttp-Selected-Transport=[http/1.1], OkHttp-Sent-Millis=[1400079441802], Server=[Microsoft-IIS/8.0], Vary=[Accept-Encoding], X-AspNet-Version=[4.0.30319], X-Powered-By=[ASP.NET], X-Powered-By-Plesk=[PleskWin]}
05-14 17:57:22.239: D/FileTransfer(2125): got response from server
05-14 17:57:22.239: D/FileTransfer(2125): 0
05-14 17:57:22.334: D/dalvikvm(2125): GC_CONCURRENT freed 778K, 72% free 12691K/45063K, paused 5ms+4ms, total 29ms
05-14 17:
</code></pre>
<p>my config.xml has <code><access origin="*"/></code> in it, and manifest file has <code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></code>.</p>
<p>I get a response "0" from the server, which means it didn't get any of the files. But on the other hand, logcat says "Sent 358920 of 358920".</p>
<p>Any help solving this would be greatly appreciated.</p>
| 3 | 3,100 |
Integrating Facebook Audience Network in Xamarin
|
<p>I have been trying to integrate Facebook Audience Network so as to load native ads in my Xamarin Native iOS application. When I debug my application the code enters method "NativeAdDidFail" and the NSError says "No fill" and No other information is printed in the console.</p>
<p>This is what I have done:</p>
<ol>
<li>Created a resource in business manager and Selected iOS as the target platform.</li>
<li>I left out the payment/mediation and app store URL since my app is not published.</li>
<li>Added an ad placement for native ads and Added one test device in the Monetization manager by adding my iphones IDFA.</li>
<li>Enabled testing, Checked the checkbox for "use real ads", I also clicked on the "choose ad type" <strong>but it doesnt seem to be saved?</strong></li>
<li>Added one test user in business manager and Assigned access to the created property.</li>
<li>Downloaded native Facebook app and Enabled tracking in the background for the native facebook app.</li>
<li>Logged in on the native app with the email of the test user that I added.</li>
<li>Added "SkadNetworkIdentifier" and LSApplicationQueriesSchemes in info.plist-> v9wttpbfk9.skadnetwork & n38lu8286q.skadnetwork</li>
<li>Downloaded Xamarin.Facebook.Audiencenetwork.ios</li>
</ol>
<p><strong>This is my code:</strong></p>
<pre><code> AdSettings.SetAdvertiserTrackingEnabled(false);
AdSettings.ClearTestDevices();
AdSettings.AddTestDevice("74312C38-4958-4187-B385-9FCFE68FRRA9");
nativeAd = new NativeAd("CAROUSEL_IMG_SQUARE_LINK#611875720420055_511995483752412")
{ Delegate = this };
nativeAd.LoadAd();
[Export("nativeAdDidLoad:")]
public void NativeAdDidLoad(NativeAd nativeAd)
{
}
[Export("nativeAd:didFailWithError:")]
public void NativeAdDidFail(NativeAd nativeAd, NSError error)
{
var errorcode = error.Code;
Console.WriteLine($"{nameof(NativeAdDidFail)} - Native ad failed to load with error: {error.LocalizedDescription}");
//AppDelegate.ShowMessage("Native Ad Error", error.LocalizedDescription, NavigationController);
}
[Export("nativeAdDidClick:")]
public void NativeAdDidClick(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdDidClick)} - Native ad was clicked.");
[Export("nativeAdDidFinishHandlingClick:")]
public void NativeAdDidFinishHandlingClick(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdDidFinishHandlingClick)} - Native ad did finish click handling.");
[Export("nativeAdWillLogImpression:")]
public void NativeAdWillLogImpression(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdWillLogImpression)} - Native ad impression is being captured.");
</code></pre>
<p>Here's <a href="https://developers.facebook.com/docs/audience-network/setting-up/testing/platform?__cft__%5B0%5D=AZXrltjw_M6dAIEONKINsrLRB35TFQf5lJz8dqcD71VyZJZJNnWrkWXhRcwbnTAfoDaxjkaABz-BxioydcsNV6l5b-IqjBZD6DKj9R_2NAkKX3p0cj7RqEOuMniIAsSuOi-sy4sDPpOuwQnZCriClU_h&__tn__=R%5D-R" rel="nofollow noreferrer">the tutorial</a> I am trying to follow</p>
<p>According to the <a href="https://developers.facebook.com/docs/audience-network/setting-up/test/checklist-errors/" rel="nofollow noreferrer">Facebook Audience Network</a>, this could be the possible reasons:</p>
<p><a href="https://i.stack.imgur.com/VIpzX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VIpzX.png" alt="enter image description here" /></a></p>
| 3 | 1,368 |
How to use Session to save value on current row of GridView, to be copied into TextBox? - VB.Net
|
<p>I'm trying to use <code>Session</code> to record the data of the 1st column of current row to be used in another Web From which will be opened using a <code>LinkButton</code> that is in the <code>GridView</code>.</p>
<p>Basically, if I click the <code>LinkButton</code> on the 1st row, the 1st column data of the 1st row will be copied to the next Web Form. But before I do that, I want to do a smaller scale experiment to test it. So instead for now I want the <code>Session</code> to copy the data into a <code>TextBox</code> in the same form.</p>
<p>For reference, here is the design of the <code>GridView</code>, most rows removed since they're not relevant:</p>
<pre><code><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" Font-Names="Arial">
<AlternatingRowStyle BackColor="#B7DBFF" />
<Columns>
<asp:BoundField DataField="caseticket" HeaderText="Ticket #" >
<HeaderStyle BackColor="#000066" ForeColor="White" Wrap="False" width="10%"/>
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<HeaderStyle BackColor="#000066" ForeColor="White" Wrap="False" width="10%"/>
<ItemTemplate>
<asp:linkbutton ID="newLog" runat="server" onclick = "CaseLog_click" >Add Log </asp:linkbutton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#000066" />
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
</code></pre>
<p>For the <code>TemplateField</code> is a <code>LinkButton</code> with a <code>onclick</code> property. With it, I created the sub:</p>
<pre><code>Sub CaseLog_click(ByVal sender As Object, ByVal e As EventArgs)
Session("ticket") = GridView1.SelectedRow.Cells(1).Text
'Response.Redirect("~/CaseLog.aspx") ==> will be using this to proceed to next Web Form
TextBox1.Text = Session("ticket") '==> For test use only.
End Sub
</code></pre>
<p>If I only kept the <code>Response.Redirect("~/CaseLog.aspx")</code> in the sub, the <code>LinkButton</code> can direct me to the next Web Form. But as it is now, during testing when I use the <code>LinkButton</code> I get an error on the <code>session</code> line of the sub.</p>
<p><code>Object reference not set to an instance of an object.</code></p>
<p>Is the code salvageable, or do I need to redo this?</p>
<p>Thanks.</p>
| 3 | 1,268 |
R-Shinny image path not working when multiple folders
|
<p>I have an R-Shinny app which displays images based on two <code>selectInput</code> as follows:</p>
<pre><code>ui<-dashboardBody(
tabItem(tabName = "title",
fluidRow(
column(6,
box(
background = "olive", width = NULL,
column(6,
selectInput("SpIDA",
"Species:",
choices = c("SELECT SPECIE",dat$Specie),
selected = "SELECT SPECIE")),
column(6,
selectInput("SpArea",
"Area:",
choices = c("SELECT AREA",dat$Area),
selected = "SELECT AREA"))
))
),
tabsetPanel(
tabPanel("title",
fluidRow(column(width = 6,
imageOutput("img.1", height = "50%")
))
))
)
)
</code></pre>
<p>I have the images stored in a local directory as "www/Specie/Area", and the image names are standard across the folders. My problem, is that when more than two areas are available for a particular specie, the images are not displayed...</p>
<p>My server section is:</p>
<pre><code>server <- function(input, output, session) {
observe({
tmp<-dat[dat$Specie == input$SpIDA,]
updateSelectInput(session,
"SpArea",
"Area:",
choices = c("SELECT AREA",tmp$Area),
selected = "SELECT AREA")
}) #Just to filter the selection SPArea selection choices based on the SpIDA
output$img.1 <- renderImage({
image_path<-file.path("www",input$SpIDA,input$SpArea,
"img1.png")
return(list(src = image_path, filetype = "image/png",width = 300))
}, deleteFile = FALSE)}
</code></pre>
<p>For species in which only one Area is available (and therefore only one folder), the image is displayed, but when there is more than one area, the app returns a blank space, but no error is thrown.</p>
<p>I believe I am correctly defining in which "Area" folder to look for, hen there is more than one option available but I have not been able to figure this one out.</p>
<p>Thanks</p>
| 3 | 1,400 |
(0x800a138f) Unhandled exception in IE8 after adding BreezeJS to Durandal project
|
<p>I'm hoping someone with some experience in Breeze/Durandal 2 on .NET 4.0 will be able to assist me with this error, as I'm pretty new to the mix.</p>
<p>I've been working on a Durandal 2/KO/Require SPA project that lately has been compiling fine and running on my IIS7. I need this app to be compatible with IE8, so I imported the shim and sham js libs as such:</p>
<pre><code> <!-- ECMAScript 5 compatibility shims for IE8 -->
<!--[if lt IE 9]>
<script src="lib/ie8/html5shiv.min.js"></script>
<script src="lib/ie8/respond.js"></script>
<script src="lib/ie8/es5-shim.min.js"></script>
<script src="lib/ie8/es5-sham.min.js"></script>
<![endif]-->
<script src="lib/jquery/jquery-1.9.1.min.js"></script>
<script src="lib/knockout/knockout-3.1.0.js"></script>
<script src="/Scripts/q.min.js"></script>
<script src="/Scripts/breeze.debug.js"></script>
<script src="lib/bootstrap/js/bootstrap.js"></script>
</code></pre>
<p>I also need to be able to access data from a DB so I tried adding BreezeJS to the mix. According to Breeze's documentation, in order for this to work I had to remake the project in VS as ASP.NET MVC4 Project using the Empty Template. After that I imported the Breeze files using NuGet: </p>
<pre><code>Install-Package Breeze.WebApi
</code></pre>
<p>Then I added in my pre-existing views, controllers, libraries, css, etc. to the newly created project. Now when I compile using IE8 I get the following error. This error does not show up for Firefox or Chrome:</p>
<pre><code>Unhandled exception at line 125, column 13 in
http://localhost:64185/lib/durandal/js/composition.js
(Edited for readability)
SourceMap D:\localdev\TestMVC4\TestMVC4\lib\ie8\es5-shim.map read failed:
Could not find file 'D:\localdev\TestMVC4\TestMVC4\lib\ie8\es5-shim.map'.
SourceMap D:\localdev\TestMVC4\TestMVC4\lib\ie8\es5-sham.map read failed:
Could not find file 'D:\localdev\TestMVC4\TestMVC4\lib\ie8\es5-sham.map'.
Unhandled exception at line 125, column 13 in http://localhost:64185/lib/durandal/js/composition.js
</code></pre>
<p>0x800a138f - Microsoft JScript runtime error: 'route' is null or not an object</p>
<p>I thought this might be a compatibility issue with JQuery so I attempted different versions there. I've made sure that my DocType is set to: </p>
<pre><code><!DOCTYPE html>
</code></pre>
<p>and that I have the following meta tag:</p>
<pre><code><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
</code></pre>
<p>However I doubt either of those would cause issues with IE8 and Durandal. Has anyone else experienced a similar issue to mine? Am I experiencing this error because I haven't configured something on the MVC4 side? </p>
<p>Any advice would be greatly appreciated.</p>
<p>Thank you</p>
| 3 | 1,131 |
PDF in pop up for mobile devices
|
<p>I am working on a project using the C# MvC .NET 4.0 framework with razor.</p>
<p>I have recently jumped onto the bootstrap bandwagon (Bootstrap v3.3.4 )in order to make our website responsive. I have been trying to find a solution for making pdf's appear as a pop up once clicked. This pop up would need to be scrollable / closable.</p>
<p>I have investigated two approaches:</p>
<ol>
<li>Using a partial view / fancybox. Unfortunately all the examples that came up were purely ASP.NET, hence I could not find anything useful.</li>
<li><p>Embedding PDF's inside the bootstrap modal with an object tag. This was only partially successful: I encountered the following trhee issues whilst browsing and scrolling pdf's embedded in modals on actual mobile devices (iPhone 4S, Safari / Chrome):</p>
<ul>
<li>Scrolling the PDF too aggressively could cause the modal to crash</li>
<li>Scrolling in the modal was unreliable, sometimes the background page would scroll instead of the actual modal. Upon zooming in or out it was often impossible to scroll at all.</li>
<li>Zooming in and out of the PDF was unreliable; only worked sometimes.</li>
</ul></li>
</ol>
<p>For what its worth, below is my .cshtml modal code:</p>
<pre><code><div>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open PDF</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body scroll">
<object type="application/pdf" data="http://www.inkwelleditorial.com/pdfSample.pdf" width="500" height="650">this is not working as expected</object>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p></p>
<p>So the way I see it, either I find a way to return pdfs in a scrollable pop up fancybox / partial view or I find a way to fix the scrolling and reliability issues with the modal as it already works partially, but not reliably as stated above.</p>
<p>Any alternative suggestions as to how to get pdf's to work reliably as pop up's on mobile devices would be greatly appreciated.</p>
| 3 | 1,123 |
Writing a regular expression for my specific code
|
<p>I've been trying to get help with this for a few days now, I've asked a dozen questions, all of which get marked duplicate (Which after thorough investigation of the linked questions, I find out it's a different issue) and a few unhelpful comments. This time, I'm coming at it from a different angle.
So far, I've got this working:</p>
<pre><code>var themes = [
'red',
'pink',
'purple',
'deep-purple',
'indigo',
'blue',
'light-blue',
'cyan',
'teal',
'green',
'lime',
'khaki',
'yellow',
'amber',
'orange',
'deep-orange',
'blue-grey',
'brown',
'grey',
'dark-grey',
'black'
]
themes.forEach((theme)=>{
HTTP.get('https://www.w3schools.com/lib/w3-theme-${theme}.css', (err, res)=>{
console.log(`/*${theme}*/\n${res.content
.replace(/w3-theme/g, theme)
.replace(/w3-text-theme/g, `${theme}-text`)
.replace(/w3-border-theme/g, `${theme}-border`)
.replace(/w3-hover-theme/g, `${theme}-hover`)
.replace(/w3-hover-text-theme/g, `${theme}-hover-text`)
.replace(/w3-hover-border-theme/g, `${theme}-hover-border`)
.replace(`${theme}-action`, `btn-${theme}`)
}\n`)
})
}
</code></pre>
<p>It's output is one of these for each color:</p>
<pre><code>/*lime*/
.lime-l5 {color:#000 !important; background-color:#fcfdf3 !important}
.lime-l4 {color:#000 !important; background-color:#f5f8d7 !important}
.lime-l3 {color:#000 !important; background-color:#eaf1af !important}
.lime-l2 {color:#000 !important; background-color:#e0ea87 !important}
.lime-l1 {color:#000 !important; background-color:#d6e35f !important}
.lime-d1 {color:#000 !important; background-color:#c1d325 !important}
.lime-d2 {color:#fff !important; background-color:#acbb21 !important}
.lime-d3 {color:#fff !important; background-color:#96a41d !important}
.lime-d4 {color:#fff !important; background-color:#818c19 !important}
.lime-d5 {color:#fff !important; background-color:#6b7515 !important}
.lime-light {color:#000 !important; background-color:#fcfdf3 !important}
/*These lines need to be added via a replace statement*/
.btn-lime-light {color:#000 !important; background-color: #fcfdf3 !important}
.btn-lime-light:hover {color:#000 !important; background-color:#f5f8d7 !important; border-color:#f5f8d7 !important}
/*They aren't currently here*/
.lime-dark {color:#fff !important; background-color:#6b7515 !important}
.btn-lime {color:#fff !important; background-color:#6b7515 !important}
.lime {color:#000 !important; background-color:#cddc39 !important}
.lime-text {color:#cddc39 !important}
.lime-border {border-color:#cddc39 !important}
.lime-hover:hover {color:#000 !important; background-color:#cddc39 !important}
.lime-hover-text:hover {color:#cddc39 !important}
.lime-hover-border:hover {border-color:#cddc39 !important}
</code></pre>
<p>I have tried adding the following, in almost every variation I can fathom (I.E. Adding flags, changing notation, breaking it up, etc.): </p>
<pre><code>.replace(/(\.(.*)-l4 .*#(.*?) .*#(.*) .*}(\n.*?)*-light.*?#(.*?) .*#(.*) .*})/, `$1\n.btn-$2-light {color:#$6 !important; background-color: #$7 !important}\n.btn-$2-light:hover {color:#$3 !important; background-color:#$4 !important; border-color:#$4 !important}`)
</code></pre>
<p>To no avail, it find 0 matches contrary to <a href="https://regex101.com/r/lC0eFT/4/" rel="nofollow noreferrer">My online tests</a>. </p>
<p>My question is: How should I go about adding those 2 lines?</p>
| 3 | 1,308 |
When we submit a form, what happened?
|
<p>Actually, I just want to get a very simple web application:</p>
<ol>
<li>a form in a webpage that I can upload a file within some parameters;</li>
<li>submit the form when I choose a proper file;</li>
<li>do some calculation using these parameters in uploaded file;</li>
<li>redirect to a new webpage with the calculation result;</li>
<li>display the result in this new webpage.</li>
</ol>
<p>I use Django 1.10. </p>
<p><strong>index.html</strong> with <code><form></code> like this:</p>
<pre><code><form action="/index/result/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type=">
<div class="field">
<label for="id_file">Input File:</label>
{{ form.file }} <!--from django model-->
</div>
<p><input type="submit" value="Submit"/></p>
</form>
</code></pre>
<p><strong>result.html</strong> for display result like this:</p>
<pre><code><div id="out">
<table id="result_display" border="1px" hidden>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<!--here will display the value comes from result-->
<th id="r_name"> {{ result }} </th>
</tr>
</tbody>
</table>
</div>
</code></pre>
<p>my <strong>views.py</strong> like this:</p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from forms import UploadFileForm
# Create your views here.
@csrf_exempt
def index_view(request):
para = ''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cd = form.cleaned_data
if cd['file']:
para = cd.get('file').read().split('\r\n')
else:
return HttpResponse('Please Input a File!')
else:
return HttpResponse('Form is invalid!')
if para:
# do some calculation with para
result = {"name": "NAD"}
return redirect('result_view', result=result) # to another view 'result_view'
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
def result_view(request, result=''):
if result:
return render(request, 'result.html', {'result': result})
else:
return HttpResponse('no result!')
</code></pre>
<p>my <strong>urls.py</strong> like this:</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^index/$', index_view),
url(r'^index/result/?(?P<result>.*)/$', result_view, name='result_view'),
]
</code></pre>
<p>Here are what really confuse me a lot:</p>
<p><strong>Q1</strong>: There are two places give result url address <code><form action="/index/result/" method="post" enctype="multipart/form-data"></code> in index.html and <code>url(r'^index/result/?(?P<result>.*)/$', result, name='result'),</code> in urls.py, which one is dominated?</p>
<p><strong>Q2</strong>: How to pass data (i.e. calculation result) from <code>index_view</code> to <code>result_view</code>?
I didn't get <code>result</code> in <code>result_view</code> function using current method.</p>
| 3 | 1,569 |
LDAP binding on Windows vs. VCE
|
<p>I have been given the simple task to do Windows authentication against the AD from a Windows Compact 7 device in a C# app. Now - 14 days later I'm still struggling, so any help would be greatly appreciated.</p>
<p>Anyway - what I’ve managed to come up with so far is doing Windows authentication on my PC using the wldap32.dll. I’m far from a C++ expert, and with Visual C++ even less so, so bear with me.
Here is my C++ code:</p>
<pre><code>EXPORT_METHOD unsigned long Authenticate(char *userName, char *password, char *domain)
{
unsigned long result = 0;
unsigned short *uUserName = (unsigned short *)userName;
unsigned short *uPassword = (unsigned short *)password;
unsigned short *uDomain = (unsigned short *)domain;
PWCHAR hostName = NULL;
LDAP* pLdapConnection = NULL;
ULONG version = LDAP_VERSION3;
size_t origsize = strlen("ELLAB.COM") + 1;
size_t convertedChars = 0;
wchar_t wcstring[100];
mbstowcs_s(&convertedChars, wcstring, origsize, "ELLAB.COM", _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
hostName = wcstring;
// Initialize a session. LDAP_PORT is the default port, 389.
pLdapConnection = ldap_init(hostName, LDAP_PORT);
if (pLdapConnection == NULL)
{
#ifdef DEBUG
AfxMessageBox(_T("Unable to Init"));
#endif // DEBUG
result = 0xff;
}
else
{
// Set the version to 3.0 (default is 2.0).
result = ldap_set_option(pLdapConnection, LDAP_OPT_PROTOCOL_VERSION, (void*)&version);
if (result != LDAP_SUCCESS)
{
#ifdef DEBUG
AfxMessageBox(_T("Unable to Set Optins"));
#endif // DEBUG
}
else
{
// Connect to the server.
result = ldap_connect(pLdapConnection, NULL);
if (result != LDAP_SUCCESS)
{
#ifdef DEBUG
AfxMessageBox(_T("Unable to Connect"));
#endif // DEBUG
}
else
{
// Be aware that the password itself is never sent over the network, and encryption is not used.
SEC_WINNT_AUTH_IDENTITY NtAuthIdentity;
ZeroMemory(&NtAuthIdentity, sizeof(NtAuthIdentity));
NtAuthIdentity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
NtAuthIdentity.Domain = uDomain;
NtAuthIdentity.DomainLength = sizeof(uDomain);
NtAuthIdentity.User = uUserName;
NtAuthIdentity.UserLength = sizeof(uUserName);
NtAuthIdentity.Password = uPassword;
NtAuthIdentity.PasswordLength = sizeof(uPassword);
//if (ldap_bind_s(pLdapConnection, NULL, NULL, LDAP_AUTH_NEGOTIATE) == LDAP_SUCCESS)
result = ldap_bind_s(pLdapConnection, NULL, (PWCHAR)&NtAuthIdentity, LDAP_AUTH_NTLM);
//if (result != LDAP_SUCCESS)
{
#ifdef DEBUG
AfxMessageBox(_T("Unable to Bind using ldap_bind_s"));
#endif // DEBUG
result = ldap_bind(pLdapConnection, NULL, (PWCHAR)&NtAuthIdentity, LDAP_AUTH_NTLM);
if (result != LDAP_SUCCESS)
{
#ifdef DEBUG
AfxMessageBox(_T("Unable to Bind using ldap_bind"));
#endif // DEBUG
}
}
}
}
// Normal cleanup and exit.
ldap_unbind(pLdapConnection);
}
return result;
}
</code></pre>
<p>And my C# sample wrapper:</p>
<pre><code>[DllImport(@"C:\Users\ckbn.ELLAB\Documents\Visual Studio 2015\Projects\WCE7_LDAP\Debug\LDAPHandler.dll", CharSet = CharSet.Unicode)]
public static extern int Authenticate(string userName, string password, string domain);
private void buttonAuthenticate_Click(object sender, EventArgs e)
{
try
{
textBoxResult.Text = "";
LDAPReturns result = (LDAPReturns)Authenticate(textBoxUserName.Text, textBoxPassword.Text, textBoxDomain.Text);
switch (result)
{
case LDAPReturns.LDAP_SUCCESS:
textBoxResult.Text = "User '" + textBoxUserName.Text + "' is authenticated";
break;
default:
textBoxResult.Text = result.ToString();
break;
}
}
catch (Exception ex) { textBoxResult.Text = "Failed: " + ex.ToString(); }
}
</code></pre>
<p>So - using the above code I can authenticate with my own credentials on my PC. Running the same code on the WCE device, I can connect to the AD server, but when I try to ldap_bind_s, it returns LDAP_AUTH_METHOD_NOT_SUPPORTED. So I’m thinking the the ARM version of the wldap32.dll is different from the x86 version. </p>
<p>Then I tried to use the ldap_bind (without ‘_s’) method. This is not working nighter on my PC nor on the WCE device and always returns 0xFFFF_FFFF.</p>
<p>So basically my questions are:</p>
<p>What does LDAP_AUTH_METHOD_NOT_SUPPORTED means, and what other methods do I have on a WCE7 device? and</p>
<p>What does it means when ldap_bind returns 0xFFFF_FFFF?</p>
<p>But any input or suggestion would be highly appreciated. Thanks in advance!</p>
| 3 | 2,492 |
Rss Reader giving Android Runtime Error
|
<p>I'm building a RSS/Atom feed reader which check different tag and takes in only the tags that we need.</p>
<p>However, when I execute the code, I'm having an Android RunTime Exception.</p>
<pre><code>04-29 23:56:20.745: D/ProgressBar(18432): setProgressDrawable mProgressDrawable = null, d = android.graphics.drawable.LayerDrawable@42347548needUpdate = false
04-29 23:56:20.745: D/ProgressBar(18432): setProgressDrawable drawableHeight = 32
04-29 23:56:20.745: D/ProgressBar(18432): setProgress = 0
04-29 23:56:20.745: D/ProgressBar(18432): setProgress = 0, fromUser = false
04-29 23:56:20.745: D/ProgressBar(18432): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:20.755: D/ProgressBar(18432): setProgress = 0
04-29 23:56:20.755: D/ProgressBar(18432): setProgress = 0, fromUser = false
04-29 23:56:20.755: D/ProgressBar(18432): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:20.865: D/libEGL(18432): loaded /vendor/lib/egl/libEGL_adreno.so
04-29 23:56:20.875: D/libEGL(18432): loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
04-29 23:56:20.885: D/libEGL(18432): loaded /vendor/lib/egl/libGLESv2_adreno.so
04-29 23:56:20.885: I/Adreno-EGL(18432): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: LNXBUILD_AU_LINUX_ANDROID_JB_3.2.4.04.03.00.173.012+PATCH[ES]_msm8226_JB_3.2.4__release_ENGG ()
04-29 23:56:20.885: I/Adreno-EGL(18432): OpenGL ES Shader Compiler Version: 20.00.01
04-29 23:56:20.885: I/Adreno-EGL(18432): Build Date: 02/27/14 Thu
04-29 23:56:20.885: I/Adreno-EGL(18432): Local Branch:
04-29 23:56:20.885: I/Adreno-EGL(18432): Remote Branch: quic/jb_3.2.4
04-29 23:56:20.885: I/Adreno-EGL(18432): Local Patches: 7de55685a2714b78da20f2a126b0dd72b0d2c0c4 Merge "PROFILER: fix default enabled/disabled setting"
04-29 23:56:20.885: I/Adreno-EGL(18432): 75d04ab84c7a68c72d92d59aae1827fcfef44b91 PROFILER: fix default enabled/disabled setting
04-29 23:56:20.885: I/Adreno-EGL(18432): Reconstruct Branch: LOCAL_PATCH[ES]
04-29 23:56:20.925: D/OpenGLRenderer(18432): Enabling debug mode 0
04-29 23:56:20.925: D/ProgressBar(18432): updateDrawableBounds: left = 0
04-29 23:56:20.925: D/ProgressBar(18432): updateDrawableBounds: top = 0
04-29 23:56:20.925: D/ProgressBar(18432): updateDrawableBounds: right = 96
04-29 23:56:20.925: D/ProgressBar(18432): updateDrawableBounds: bottom = 32
04-29 23:56:20.925: D/ProgressBar(18432): updateDrawableBounds: mProgressDrawable.setBounds()
04-29 23:56:21.885: D/ProgressBar(18432): setProgress = 1
04-29 23:56:21.885: D/ProgressBar(18432): setProgress = 1, fromUser = false
04-29 23:56:21.885: D/ProgressBar(18432): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.895: D/ProgressBar(18432): setProgress = 2
04-29 23:56:21.895: D/ProgressBar(18432): setProgress = 2, fromUser = false
04-29 23:56:21.895: D/ProgressBar(18432): mProgress = 1mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.895: D/ProgressBar(18432): setProgress = 3
04-29 23:56:21.895: D/ProgressBar(18432): setProgress = 3, fromUser = false
04-29 23:56:21.895: D/ProgressBar(18432): mProgress = 2mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.905: D/ProgressBar(18432): setProgress = 4
04-29 23:56:21.905: D/ProgressBar(18432): setProgress = 4, fromUser = false
04-29 23:56:21.905: D/ProgressBar(18432): mProgress = 3mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.945: D/ProgressBar(18432): setProgress = 5
04-29 23:56:21.945: D/ProgressBar(18432): setProgress = 5, fromUser = false
04-29 23:56:21.945: D/ProgressBar(18432): mProgress = 4mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.955: D/ProgressBar(18432): setProgress = 6
04-29 23:56:21.955: D/ProgressBar(18432): setProgress = 6, fromUser = false
04-29 23:56:21.955: D/ProgressBar(18432): mProgress = 5mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.955: D/ProgressBar(18432): setProgress = 7
04-29 23:56:21.955: D/ProgressBar(18432): setProgress = 7, fromUser = false
04-29 23:56:21.955: D/ProgressBar(18432): mProgress = 6mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.965: D/ProgressBar(18432): setProgress = 8
04-29 23:56:21.965: D/ProgressBar(18432): setProgress = 8, fromUser = false
04-29 23:56:21.965: D/ProgressBar(18432): mProgress = 7mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.975: D/ProgressBar(18432): setProgress = 9
04-29 23:56:21.975: D/ProgressBar(18432): setProgress = 9, fromUser = false
04-29 23:56:21.975: D/ProgressBar(18432): mProgress = 8mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.985: D/ProgressBar(18432): setProgress = 10
04-29 23:56:21.985: D/ProgressBar(18432): setProgress = 10, fromUser = false
04-29 23:56:21.985: D/ProgressBar(18432): mProgress = 9mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.985: D/ProgressBar(18432): setProgress = 11
04-29 23:56:21.985: D/ProgressBar(18432): setProgress = 11, fromUser = false
04-29 23:56:21.985: D/ProgressBar(18432): mProgress = 10mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:21.995: D/ProgressBar(18432): setProgress = 12
04-29 23:56:21.995: D/ProgressBar(18432): setProgress = 12, fromUser = false
04-29 23:56:21.995: D/ProgressBar(18432): mProgress = 11mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.015: D/ProgressBar(18432): setProgress = 13
04-29 23:56:22.015: D/ProgressBar(18432): setProgress = 13, fromUser = false
04-29 23:56:22.015: D/ProgressBar(18432): mProgress = 12mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.015: D/ProgressBar(18432): setProgress = 14
04-29 23:56:22.015: D/ProgressBar(18432): setProgress = 14, fromUser = false
04-29 23:56:22.015: D/ProgressBar(18432): mProgress = 13mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.025: D/ProgressBar(18432): setProgress = 15
04-29 23:56:22.025: D/ProgressBar(18432): setProgress = 15, fromUser = false
04-29 23:56:22.025: D/ProgressBar(18432): mProgress = 14mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.035: D/ProgressBar(18432): setProgress = 16
04-29 23:56:22.035: D/ProgressBar(18432): setProgress = 16, fromUser = false
04-29 23:56:22.035: D/ProgressBar(18432): mProgress = 15mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.045: D/ProgressBar(18432): setProgress = 17
04-29 23:56:22.045: D/ProgressBar(18432): setProgress = 17, fromUser = false
04-29 23:56:22.045: D/ProgressBar(18432): mProgress = 16mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.045: D/ProgressBar(18432): setProgress = 18
04-29 23:56:22.045: D/ProgressBar(18432): setProgress = 18, fromUser = false
04-29 23:56:22.045: D/ProgressBar(18432): mProgress = 17mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.065: D/ProgressBar(18432): setProgress = 19
04-29 23:56:22.065: D/ProgressBar(18432): setProgress = 19, fromUser = false
04-29 23:56:22.065: D/ProgressBar(18432): mProgress = 18mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.075: D/ProgressBar(18432): setProgress = 20
04-29 23:56:22.075: D/ProgressBar(18432): setProgress = 20, fromUser = false
04-29 23:56:22.075: D/ProgressBar(18432): mProgress = 19mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.075: D/ProgressBar(18432): setProgress = 21
04-29 23:56:22.075: D/ProgressBar(18432): setProgress = 21, fromUser = false
04-29 23:56:22.075: D/ProgressBar(18432): mProgress = 20mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.085: D/ProgressBar(18432): setProgress = 22
04-29 23:56:22.085: D/ProgressBar(18432): setProgress = 22, fromUser = false
04-29 23:56:22.085: D/ProgressBar(18432): mProgress = 21mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.095: D/ProgressBar(18432): setProgress = 23
04-29 23:56:22.095: D/ProgressBar(18432): setProgress = 23, fromUser = false
04-29 23:56:22.095: D/ProgressBar(18432): mProgress = 22mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.095: D/ProgressBar(18432): setProgress = 24
04-29 23:56:22.095: D/ProgressBar(18432): setProgress = 24, fromUser = false
04-29 23:56:22.095: D/ProgressBar(18432): mProgress = 23mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.105: D/ProgressBar(18432): setProgress = 25
04-29 23:56:22.105: D/ProgressBar(18432): setProgress = 25, fromUser = false
04-29 23:56:22.105: D/ProgressBar(18432): mProgress = 24mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.115: D/ProgressBar(18432): setProgress = 100
04-29 23:56:22.115: D/ProgressBar(18432): setProgress = 100, fromUser = false
04-29 23:56:22.115: D/ProgressBar(18432): mProgress = 25mIndeterminate = false, mMin = 0, mMax = 100
04-29 23:56:22.115: D/AndroidRuntime(18432): Shutting down VM
04-29 23:56:22.115: W/dalvikvm(18432): threadid=1: thread exiting with uncaught exception (group=0x41758898)
04-29 23:56:22.125: E/AndroidRuntime(18432): FATAL EXCEPTION: main
04-29 23:56:22.125: E/AndroidRuntime(18432): java.lang.NullPointerException
04-29 23:56:22.125: E/AndroidRuntime(18432): at com.itcuties.app.SplashActivity$GetRSSDataTask.onPostExecute(SplashActivity.java:81)
04-29 23:56:22.125: E/AndroidRuntime(18432): at com.itcuties.app.SplashActivity$GetRSSDataTask.onPostExecute(SplashActivity.java:1)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.os.AsyncTask.finish(AsyncTask.java:631)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.os.Looper.loop(Looper.java:176)
04-29 23:56:22.125: E/AndroidRuntime(18432): at android.app.ActivityThread.main(ActivityThread.java:5493)
04-29 23:56:22.125: E/AndroidRuntime(18432): at java.lang.reflect.Method.invokeNative(Native Method)
04-29 23:56:22.125: E/AndroidRuntime(18432): at java.lang.reflect.Method.invoke(Method.java:525)
04-29 23:56:22.125: E/AndroidRuntime(18432): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
04-29 23:56:22.125: E/AndroidRuntime(18432): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
04-29 23:56:22.125: E/AndroidRuntime(18432): at dalvik.system.NativeStart.main(Native Method)
04-29 23:57:07.065: I/Process(18432): Sending signal. PID: 18432 SIG: 9
</code></pre>
<p>Here's my java File which does that,</p>
<pre><code>package com.itcuties.app.util.atom;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import android.widget.ProgressBar;
import com.itcuties.app.reader.data.RssAtomItem;
import com.itcuties.app.util.text.TextConverter;
public class RssAtomParseHandler extends DefaultHandler {
private List<RssAtomItem> rssItems;
// Used to reference item while parsing
private RssAtomItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// Parsing contents indicator
private boolean parsingContents;
// Parsing published date indicator
private boolean parsingPublishedDate;
// A buffer for title contents
private StringBuffer currentTitleSb;
// A buffer for content tag contents
private StringBuffer currentContentSb;
// A buffer for publish date tag contents;
private StringBuffer currentPubishDateSb;
// Parsing published Author name
private boolean parsingAuthorName;
// A buffer for Author Name
private StringBuffer currentAuthorSb;
// This is a ProgressBar reference set by the SplashScreen
// We use it to show the real progress while each item from
// the feed is read.
private ProgressBar progressBar;
public RssAtomParseHandler() {
rssItems = new ArrayList<RssAtomItem>();
}
public List<RssAtomItem> getItems() {
return rssItems;
}
public void setProgressBar(ProgressBar progressBar) {
this.progressBar = progressBar;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("entry".equals(qName)) {
currentItem = new RssAtomItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
} else if ("author".equals(qName)) {
parsingAuthorName = true;
currentAuthorSb = new StringBuffer();
} else if ("content".equals(qName)) {
parsingContents = true;
currentContentSb = new StringBuffer();
} else if ("published".equals(qName)) {
parsingPublishedDate = true;
currentPubishDateSb = new StringBuffer();
} else if ("category".equals(qName)) {
if (currentItem != null && currentItem.getCategory() == null) {
currentItem.setCategory(attributes.getValue("term"));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("entry".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
// There is a title tag for a whole channel present.
// It is being parsed before the entry tag is present,
// so we need to check if item is not null
if (currentItem != null)
// We encode the title so that it can be read by the application
// properly
currentItem.setTitle(TextConverter.convertTitle(currentTitleSb
.toString()));
} else if ("content".equals(qName)) {
parsingContents = false;
if (currentItem != null) {
// When an item's content is being set we convert it a little
// bit:
// - All styles and JavaScript information are removed
// - Content is URL encoded so that the WebView component can
// display it correctly
// - We remove two sections which are added by the ATOM feed,
// the post info section
// and the code download section (only github link is present in
// the text)
currentItem.setContent(TextConverter
.clearStylesAndJS(TextConverter.URLEncode(TextConverter
.removePostInfoSection(TextConverter
.removeDownloadSection(currentContentSb
.toString())))));
// Update progressBar
progressBar.setProgress(progressBar.getProgress() + 1);
} else if ("author".equals(qName)) {
parsingAuthorName = false;
if (currentItem != null) {
currentItem.setAuthor(currentAuthorSb.toString());
// Update progressBar
progressBar.setProgress(progressBar.getProgress() + 1);
}
} else if ("published".equals(qName)) {
parsingPublishedDate = false;
if (currentItem != null)
try {
// We convert the date from the WordPress format to
// DD-MM-YYYY format
currentItem.setPublishDate(TextConverter
.convertDate(currentPubishDateSb.toString()));
} catch (ParseException e) {
currentItem.setPublishDate("no date");
Log.e("ITCRssReader", "No publish date available");
}
}
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// title, contents and date tags contents values are set here.
// This method can be called multiple times for one tag, it depends
// on how much text tag's contents has. Remember that SAX is a
// stream parser so it parses feed stream sequentially.
if (parsingTitle) {
if (currentItem != null)
currentTitleSb.append(new String(ch, start, length));
} else if (parsingAuthorName) {
if (currentItem != null)
currentAuthorSb.append(new String(ch, start, length));
else if (parsingContents) {
if (currentItem != null)
currentContentSb.append(new String(ch, start, length));
} else if (parsingPublishedDate) {
if (currentItem != null)
currentPubishDateSb.append(new String(ch, start, length));
}
}
}
}
</code></pre>
<p>Here's the Splash Activity that uses AsyncTask.</p>
<pre><code>package com.itcuties.app;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.itcuties.app.reader.data.RssAtomItem;
import com.itcuties.app.reader.data.RssResults;
import com.itcuties.app.util.atom.RssAtomReader;
/**
* Application splash screen. It also loads data.
*
*/
public class SplashActivity extends Activity {
private ProgressBar progressBar;
private Toast t;
String done ="Done!";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.setProgress(0); // No progress so far
// Download data in the new thread
GetRSSDataTask grdt = new GetRSSDataTask();
grdt.execute("[Feed Address goes here]");
}
/**
* Read RSS channel data.
*
*
*/
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssAtomItem> > {
@Override
protected List<RssAtomItem> doInBackground(String... urls) {
try {
// Create RSS reader
RssAtomReader rssReader = new RssAtomReader(urls[0]);
rssReader.setProgressBar(progressBar); // Set the progress bar to show real progress
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("BlanketCoffeeRSS", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(List<RssAtomItem> results) {
// When the download is done the main activity needs to be started
Intent i = new Intent(SplashActivity.this, ListPostsActivity.class);
// You might find this not right to use a static attribute to pass data between the
// the activities in the application. We tried to pass the List of the RssAtomItem
// object with no luck although RssAtomItem implemented Serializable interface.
// ListPostActivity read null values. So this is the engineer's solution. It works :)
RssResults.setResults(results); //We need to set the results of the download process
// Show 100% progress
progressBar.setProgress(100);
t.setText(done);
t.show();
// Start new activity and finish this splash activity
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
}
}
</code></pre>
<p>Can Anybody tell me where am I doing it wrong? The number of author tags are 50, as supposed to the 15 odd posts. Is that creating a problem or something else?</p>
| 3 | 8,389 |
MonoMac Create Mac Installer results in Merging Mono Failed. FATAL UNHANDLED EXCEPTION
|
<p>I am using MonoDevelop 2.8.8.4 and MonoFramework (MDK) 2.10.9_8. I'm also using Mac OSX Lion 10.7.3 and have installed XCode 4.3.1 for Lion SDK. My MonoMac application runs fine when debugging with MonoDevelop. Then I tried to create the Application Bundle by going to Project -> Create Mac Installer... </p>
<p>"Include Mono in Application Bundle" is checked</p>
<p>Linker: is set to "Don't link assemblies"</p>
<p>Everything else is unchecked and grayed out.</p>
<p>When I hit "Create Package" then "Save", MonoDevelop begins to create the bundle but then it fails with:</p>
<pre><code>Unhandled Exception: System.ComponentModel.Win32Exception: ApplicationName='gcc', CommandLine='-mmacosx-version-min=10.5 -m32 /tmp/monomac-build-634690657739224650/AboutToBlowUpDemo.app/Contents/MacOS/driver.m -o /tmp/monomac-build-634690657739224650/AboutToBlowUpDemo.app/Contents/MacOS/AboutToBlowUpDemo -D_THREAD_SAFE -I/Library/Frameworks/Mono.framework/Versions/2.10.9/include/mono-2.0 /Library/Frameworks/Mono.framework/Versions/2.10.9/lib/libmono-2.0.a -framework AppKit -liconv', CurrentDirectory=''
at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
at System.Diagnostics.Process.Start (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.RunCommand (System.String path, System.String args, System.String[] env, System.String& output) [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.Compile () [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ComponentModel.Win32Exception: ApplicationName='gcc', CommandLine='-mmacosx-version-min=10.5 -m32 /tmp/monomac-build-634690657739224650/AboutToBlowUpDemo.app/Contents/MacOS/driver.m -o /tmp/monomac-build-634690657739224650/AboutToBlowUpDemo.app/Contents/MacOS/AboutToBlowUpDemo -D_THREAD_SAFE -I/Library/Frameworks/Mono.framework/Versions/2.10.9/include/mono-2.0 /Library/Frameworks/Mono.framework/Versions/2.10.9/lib/libmono-2.0.a -framework AppKit -liconv', CurrentDirectory=''
at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
at System.Diagnostics.Process.Start (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.RunCommand (System.String path, System.String args, System.String[] env, System.String& output) [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.Compile () [0x00000] in <filename unknown>:0
at MonoMac.Bundler.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0
</code></pre>
<p>mmp exited with code 1 </p>
<p>Merging Mono failed</p>
<p>I've also tried every other combination in the "Create Mac Installer…" window but I always get the same error. Can anybody tell me what I'm doing wrong?</p>
| 3 | 1,261 |
Problem with import javax.persistence.EntityManager;
|
<p>Hey I want to make projects using databases. I've found some tutorials on youtube, but I have problem with Java JPA/Hibernate. Even tho I am following each step I just cant get to import in my class</p>
<pre><code>import javax.persistence.EntityManage
</code></pre>
<p>I am using IntelliJ and here is how I am trying to do it.
First I create maven project without archetypes.
Then in my pom.xml file which for some reason looks different than the one in tutorial.</p>
<p>I am adding dependencies.</p>
<pre><code><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</code></pre>
<p>The second one might not be needed, but I am trying everything at this point. At the end my pom.xml file looks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>BD</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
</dependencies>
</project>
</code></pre>
<p>In my pom file there are no errors.
I have also made persistence.xml file, but the problem appears before it matters.
I've spent few hours looking for solution and I am so angry at myself that I cant get over such a easy thing, but I have no idea what am I doing wrong. I literally follow tutorial that clearly works.</p>
| 3 | 1,226 |
Selenium 'dies' when visiting some websites using Behat / Mink
|
<p>I'm trying to create a a custom scenario in Behat / Mink using the javascript capabilities of Selenium but I've hit a peculiar snag. I've stripped everything back to the bare bones to lay the problem out as simply as possible but in summary when calling visit() in Selenium, some websites run fine but other (including my own) return the error "Error communicating with the remote browser. It may have died." in behat which terminates the scenario.</p>
<p>In detail:</p>
<p>My behat.yml file looks like this:</p>
<pre><code>default:
paths:
features: features
bootstrap: %behat.paths.features%/bootstrap
extensions:
Behat\MinkExtension\Extension:
base_url: http://www.foo.bar
goutte: ~
selenium2:
browser: 'firefox'
</code></pre>
<p>In my FeatureContext.php file I have the following custom function:</p>
<pre><code>public function iAmLoggedIn()
{
$session = $this->getSession();
$session->visit("http://www.foo.bar");
{
</code></pre>
<p>Now when I run the scenario in Behat that uses the custom function I get the following error:</p>
<pre><code>PHP Fatal error: Uncaught exception 'WebDriver\Exception\UnknownError' with message 'Error communicating with the remote browser. It may have died.
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
Driver info: driver.version: EventFiringWebDriver' in /var/www/behat/vendor/instaclick/php-webdriver/lib/WebDriver/Exception.php:157
Stack trace:
#0 /var/www/behat/vendor/instaclick/php-webdriver/lib/WebDriver/AbstractWebDriver.php(140): WebDriver\Exception::factory(13, 'Error communica...')
#1 /var/www/behat/vendor/instaclick/php-webdriver/lib/WebDriver/Session.php(151): WebDriver\AbstractWebDriver->curl('DELETE', '')
#2 /var/www/behat/vendor/behat/mink-selenium2-driver/src/Behat/Mink/Driver/Selenium2Driver.php(292): WebDriver\Session->close()
#3 /var/www/behat/vendor/behat/mink/src/Behat/Mink/Session.php(70): Behat\Mink\Driver\Selenium2Dri in /var/www/behat/vendor/behat/mink-selenium2-driver/src/Behat/Mink/Driver/Selenium2Driver.php on line 294
</code></pre>
<p>But here's the oddity: thinking that this may have been an issue with my website (www.foo.bar) I tried a different website by editing the line on the function:</p>
<pre><code>$session->visit("http://www.bbc.co.uk");
</code></pre>
<p>This time no error and the scenario continues as normal. Good old BBC. To make sure I also tried Goole:</p>
<pre><code>$session->visit("http://www.google.com");
</code></pre>
<p>But this time I get exactly the same error: 'Error communicating with the remote browser. It may have died.'. Weird. So I try a number of other websites, some work fine, others return this error. There doesn't seem to be any obvious similarity between those sites that kill Selenium, and those that don't. So what is Selenium saying?</p>
<p>Output from a site that returns the 'It may have died' error:</p>
<pre><code>11:41:41.428 INFO - Executing: [new session: Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]])
11:41:41.430 INFO - Creating a new session for Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]
11:41:44.024 INFO - Done: [new session: Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]]
11:41:44.031 INFO - Executing: [get: http://www.foo.bar//])
11:41:50.478 INFO - Executing: [delete all cookies])
11:41:50.494 INFO - Executing: [delete session: cee7cfa5-bc53-4804-a9a4-f6b52b0f48df])
</code></pre>
<p>Output from a site that does not return the error:</p>
<pre><code>11:19:19.930 INFO - Executing: [new session: Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]])
11:19:19.936 INFO - Creating a new session for Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]
11:19:24.607 INFO - Done: [new session: Capabilities [{platform=ANY, browserVersion=8, browserName=firefox, deviceType=tablet, selenium-version=2.31.0, name=Behat test, browser=firefox, deviceOrientation=portrait, max-duration=300, version=8}]]
11:19:24.614 INFO - Executing: [get: http://www.bbc.co.uk/])
11:19:43.454 INFO - Done: [get: http://www.bbc.co.uk/]
11:19:43.463 INFO - Executing: [delete all cookies])
11:19:46.263 INFO - Done: [delete all cookies]
11:19:49.935 INFO - Executing: [delete all cookies])
11:19:49.955 INFO - Done: [delete all cookies]
11:19:50.389 INFO - Executing: [delete session: a092aa77-ad26-4f6f-8fc1-f290b688d7fa])
11:19:50.488 INFO - Done: [delete session: a092aa77-ad26-4f6f-8fc1-f290b688d7fa]
</code></pre>
<p>No clue there apart from the fact that Selenium completes the 'get' of bbc.co.uk but not of foo.bar. So what about the access logs for foo.bar? They seem normal:</p>
<pre><code>10.179.?.? - - [06/Jan/2015:10:52:57 +0000] "GET / HTTP/1.1" 401 486 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
10.179.?.? - tester [06/Jan/2015:10:52:57 +0000] "GET / HTTP/1.1" 200 33141 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
10.179.?.? - tester [06/Jan/2015:10:53:00 +0000] "GET /css/page_specific_css/index.css HTTP/1.1" 200 10234 "http://www.foo.bar/" "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
10.179..?.? - tester [06/Jan/2015:10:53:00 +0000] "GET /library/jquery-tools.min.js HTTP/1.1" 200 5920 "http://www.foo.bar/" "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
</code></pre>
<p>10.179.?.? being the IP of the CI server so it's communicating with the server fine and retrieving all the assets. So I'm not sure if this is a Selenium issue or a Behat / Mink issue but I'm at a loss. There doesn't seem to be any logical reason why some sites work and other's don't. Any help would be greatly appreciated.</p>
| 3 | 2,332 |
Leiningen isn't checking Maven directory
|
<p>I have a Clojure project that I'm writing using Intellij and the Cursive and Leiningen plugins.</p>
<p>My problem is, Leiningen isn't checking the central Maven directory when finding dependencies. <code>water-time</code> is my current project, and <code>helpers</code> is the project containing "helper" functions that I want to include.</p>
<p>First, my file structure:</p>
<ul>
<li>IdeaProjects
<ul>
<li>helpers
<ul>
<li>project.clj</li>
<li>src
<ul>
<li>helpers
<ul>
<li>general_helpers.clj</li>
</ul></li>
</ul></li>
</ul></li>
<li>water-timer
<ul>
<li>project.clj</li>
<li>src
<ul>
<li>water_timer
<ul>
<li>tone_producer.clj</li>
</ul></li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>helper's project.clj:</p>
<pre><code>(defproject helpers "1"
:description "General Helper Library"
:dependencies [[org.clojure/clojure "1.8.0"]])
</code></pre>
<p>water-timer's project.clj:</p>
<pre><code>(defproject water-timer "1"
:description "A timer that reminds you to drink water"
:dependencies [[org.clojure/clojure "1.8.0"]
[helpers "1"]]
:main water-timer.tone-producer
:aot [water-timer.tone-producer])
</code></pre>
<p>tone_producer.clj with irrelevant bits removed:</p>
<pre><code>(ns tone-producer
(:require [general-helpers :as g])
(:gen-class))
(defn -main [& args]
(println "Test!"))
</code></pre>
<p>Both projects were created using <code>lein new</code>. I had originally created them using Intellij, but in my <a href="https://stackoverflow.com/questions/38329515/cant-build-a-jar-using-leiningen">previous question</a>, it was recommended that I create the projects using leiningen, and then import them, so I recreated them from scratch.</p>
<p>If I then cd into <code>helpers</code> and run <code>lein install</code>, it successfully installs <code>helpers</code> into the Maven directory (<code>[my-name]\.m2\repository\helpers\helpers\1\helpers-1.jar</code>).</p>
<p>When I try to use the files though (by trying to create a uberjar using leiningen), it complains that it can't find the dependencies; even if I run <code>lein deps</code> prior:</p>
<pre><code>"C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.2\jre\jre\bin\java" -Dvisualvm.id=91626738132760 -Dfile.encoding=UTF-8 -Dmaven.wagon.http.ssl.easy=false -Dmaven.wagon.rto=10000 -Didea.launcher.port=7541 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.2\bin" -classpath "C:\Users\slomi\.lein\self-installs\leiningen-2.6.1-standalone.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain clojure.main -m leiningen.core.main uberjar
Compiling water-timer.tone-producer
java.io.FileNotFoundException: Could not locate general_helpers__init.class or general_helpers.clj on classpath. Please check that namespaces with dashes use underscores in the Clojure file name., compiling:(tone_producer.clj:1:1)
Exception in thread "main" java.io.FileNotFoundException: Could not locate general_helpers__init.class or general_helpers.clj on classpath. Please check that namespaces with dashes use underscores in the Clojure file name., compiling:(tone_producer.clj:1:1)
at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3657)
at clojure.lang.Compiler.compile1(Compiler.java:7474)
at clojure.lang.Compiler.compile1(Compiler.java:7464)
at clojure.lang.Compiler.compile(Compiler.java:7541)
at clojure.lang.RT.compile(RT.java:406)
at clojure.lang.RT.load(RT.java:451)
at clojure.lang.RT.load(RT.java:419)
at clojure.core$load$fn__5677.invoke(core.clj:5893)
at clojure.core$load.invokeStatic(core.clj:5892)
at clojure.core$load.doInvoke(core.clj:5876)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.core$load_one.invokeStatic(core.clj:5697)
at clojure.core$compile$fn__5682.invoke(core.clj:5903)
at clojure.core$compile.invokeStatic(core.clj:5903)
at clojure.core$compile.invoke(core.clj:5895)
at user$eval20$fn__29.invoke(form-init7018212669773798479.clj:1)
at user$eval20.invokeStatic(form-init7018212669773798479.clj:1)
at user$eval20.invoke(form-init7018212669773798479.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6927)
at clojure.lang.Compiler.eval(Compiler.java:6917)
at clojure.lang.Compiler.eval(Compiler.java:6917)
at clojure.lang.Compiler.load(Compiler.java:7379)
at clojure.lang.Compiler.loadFile(Compiler.java:7317)
at clojure.main$load_script.invokeStatic(main.clj:275)
at clojure.main$init_opt.invokeStatic(main.clj:277)
at clojure.main$init_opt.invoke(main.clj:277)
at clojure.main$initialize.invokeStatic(main.clj:308)
at clojure.main$null_opt.invokeStatic(main.clj:342)
at clojure.main$null_opt.invoke(main.clj:339)
at clojure.main$main.invokeStatic(main.clj:421)
at clojure.main$main.doInvoke(main.clj:384)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:383)
at clojure.lang.AFn.applyToHelper(AFn.java:156)
at clojure.lang.Var.applyTo(Var.java:700)
at clojure.main.main(main.java:37)
Caused by: java.io.FileNotFoundException: Could not locate general_helpers__init.class or general_helpers.clj on classpath. Please check that namespaces with dashes use underscores in the Clojure file name.
at clojure.lang.RT.load(RT.java:456)
at clojure.lang.RT.load(RT.java:419)
at clojure.core$load$fn__5677.invoke(core.clj:5893)
at clojure.core$load.invokeStatic(core.clj:5892)
at clojure.core$load.doInvoke(core.clj:5876)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.core$load_one.invokeStatic(core.clj:5697)
at clojure.core$load_one.invoke(core.clj:5692)
at clojure.core$load_lib$fn__5626.invoke(core.clj:5737)
at clojure.core$load_lib.invokeStatic(core.clj:5736)
at clojure.core$load_lib.doInvoke(core.clj:5717)
at clojure.lang.RestFn.applyTo(RestFn.java:142)
at clojure.core$apply.invokeStatic(core.clj:648)
at clojure.core$load_libs.invokeStatic(core.clj:5774)
at clojure.core$load_libs.doInvoke(core.clj:5758)
at clojure.lang.RestFn.applyTo(RestFn.java:137)
at clojure.core$apply.invokeStatic(core.clj:648)
at clojure.core$require.invokeStatic(core.clj:5796)
at clojure.core$require.doInvoke(core.clj:5796)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at tone_producer$loading__5569__auto____36.invoke(tone_producer.clj:1)
at clojure.lang.AFn.applyToHelper(AFn.java:152)
at clojure.lang.AFn.applyTo(AFn.java:144)
at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3652)
... 35 more
Compilation failed: Subprocess failed
Process finished with exit code 1
</code></pre>
<p>The thing that concerns me is the classpath it prints at the top of the error doesn't include the <code>.m2</code> directory. It is my understanding that leiningen looks in that directory when trying to resolve dependencies, so I'm confused as to why it isn't looking there.</p>
<p>What am I missing here? All I want to do is make a executable jar that depends on a local source!</p>
| 3 | 2,831 |
PHP contact form verification field
|
<p>Using the script below (taken from a template), I added a simple verification question to prevent spam (What is 2 + 2?). As of now, when the submit button is filled, the error.php page appears but the form is submitted as blank. </p>
<p>How do I ensure the form is only submitted after verifying the security question? </p>
<pre><code><?php
$EmailTo = "myemail@email.com";
$Subject = "website";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$number = Trim(stripslashes($_POST['number']));
$message = Trim(stripslashes($_POST['message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $number;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$submit = mail($EmailTo, $Subject, $Body, "From: <$email>");
// redirect to success page
if(isset($_POST['submit'])){
if(isset($_POST['answer']) && $_POST['answer'] == 4){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
}
}
?>
</code></pre>
<p>The form code follows:</p>
<pre><code><div id="form-holder" class="cont">
<h2>Contact form</h2>
<form method="post" action="send.php" class="uniform get-in-touch">
<div class="i-h">
<input type="text" name="name" id="name"/>
<div class="i-l"><span>Name</span></div></div>
<div class="i-h">
<input type="email" name="email" id="email"/>
<div class="i-l"><span>E-mail</span></div></div>
<div class="i-h">
<input type="text" name="number" id="number"/>
<div class="i-l"><span>Number</span></div></div>
<div class="t-h">
<textarea name="message" rows="32" cols="8" id="message" placeholder="Please leave us a message."></textarea>
</div>
<br><p>What is 2+2?</p><input type="text" name="answer" id="answer" />
<input type="submit" name="submit" value="Submit" class="submit-button">
<a href="#" class="do-clear">Clear</a>
</form>
</div>
</code></pre>
| 3 | 1,425 |
Swift: Trying to get my statusbar back - stopping view from writing below the safespace
|
<p>I got my function:</p>
<pre><code> func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
</code></pre>
<p>And I want to minus the view.frame.height, with the height of the statusbar.
The closest thing I could find was this: <a href="https://stackoverflow.com/questions/12991935/how-to-programmatically-get-ios-status-bar-height">How to programmatically get iOS status bar height</a></p>
<p>I've tried: </p>
<blockquote>
<p>view.frame.height - [UIApplication
sharedApplication].statusBarFrame.size.height</p>
<p>view.frame.height - 20.0f</p>
<p>view.frame.height - 20</p>
</blockquote>
<p>But none of them works as I would hope. I believe it uses pixels, instead of points at the last one, the first two doesn't run at all.</p>
<p>What I'm looking for is:
view.frame.height - statusBarHeight</p>
<p>If it helps, here is my entire viewController.</p>
<pre><code>//
// SceneDelegate.swift
// BeBetterLogin 0.1
//
// Created by Samuel Hauptmann van Dam on 15/03/2020.
// Copyright © 2020 BeBetter. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
// window = UIWindow(frame: UIScreen.main.bounds)
// window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
window?.rootViewController = HomeController(collectionViewLayout: layout)
window?.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
</code></pre>
<p>And my SceneDelegate.</p>
<pre><code>//
// SceneDelegate.swift
// BeBetterLogin 0.1
//
// Created by Samuel Hauptmann van Dam on 15/03/2020.
// Copyright © 2020 BeBetter. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
// window = UIWindow(frame: UIScreen.main.bounds)
// window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
// window?.rootViewController = HomeController(collectionViewLayout: layout)
// window?.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
</code></pre>
| 3 | 2,157 |
`hibernate.hbm2ddl.import_files` property stops working if I switch the datasource from `H2` to `postgresql`
|
<p>This is the config of my spring boot app:</p>
<pre><code>@Configuration
@EnableJpaAuditing
public class Cfg {
@Bean(destroyMethod = "close")
public DataSource myDataSource() {
org.apache.tomcat.jdbc.pool.DataSource o = new org.apache.tomcat.jdbc.pool.DataSource();
o.setDriverClassName("org.h2.Driver");
o.setUrl("jdbc:h2:mem:test");
return o;
}
@Bean("entityManagerFactory")
public LocalSessionFactoryBean sessionFactory(DataSource myDataSource) {
LocalSessionFactoryBean o = new LocalSessionFactoryBean();
o.setDataSource(myDataSource);
o.setPackagesToScan("fctorial.crossover.entities");
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.format_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "none");
props.setProperty("hibernate.hbm2ddl.import_files", "classpath:/schema.sql,classpath:/data.sql");
o.setHibernateProperties(props);
return o;
}
}
</code></pre>
<p>And it works as expected, but for some reason, if I change the database to postgresql (via the following patch), the <code>import_files</code> aren't executed anymore.</p>
<pre><code>@@ -17,8 +17,10 @@
@Bean(destroyMethod = "close")
public DataSource myDataSource() {
org.apache.tomcat.jdbc.pool.DataSource o = new org.apache.tomcat.jdbc.pool.DataSource();
- o.setDriverClassName("org.h2.Driver");
- o.setUrl("jdbc:h2:mem:test");
+ o.setDriverClassName("org.postgresql.Driver");
+ o.setUsername("saga");
+ o.setPassword("");
+ o.setUrl("jdbc:postgresql://localhost:5432/postgres");
return o;
}
@@ -28,7 +30,7 @@
o.setDataSource(myDataSource);
o.setPackagesToScan("fctorial.crossover.entities");
Properties props = new Properties();
- props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
+ props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.format_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "none");
</code></pre>
<p>I have this at the top of <code>schema.sql</code>:</p>
<pre><code>NOT A VALID SQL STATEMENT;
</code></pre>
<p>The <code>h2</code> version of app throws an error at startup but the <code>postgresql</code> version starts without an error and malfunctions at runtime because the database isn't initialized correctly.</p>
<p>Note: This codebase is a a full example demonstrating this issue: <a href="https://github.com/fctorial/crud" rel="nofollow noreferrer">https://github.com/fctorial/crud</a></p>
| 3 | 1,434 |
Family tree, cannot resolve child
|
<p>I'm clueless with this task. I need to make family tree like on this </p>
<p><a href="https://i.stack.imgur.com/kFbhi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kFbhi.png" alt="enter image description here"></a></p>
<p>But I cannot solve child in Main.java. With every name I have to write null to child. </p>
<p>Here is my code : <a href="https://www.jdoodle.com/embed/v0/Q12" rel="nofollow noreferrer">Main.java</a>.
Second file: <a href="https://www.jdoodle.com/embed/v0/Q0Z" rel="nofollow noreferrer">Osoba.java</a></p>
<pre><code>public class Main {
public static void main(String[] args) {
Osoba abraham = new Osoba("Abraham Simpson", null, null, null, null, null, null, null);
Osoba penelope = new Osoba("Penelope Olsen", null, null, null, null, null, null,null);
Osoba pan = new Osoba("Pan Bouvier", null, null, null, null, null,null,null);
Osoba jackie = new Osoba("Jackie Bouvier", null, null, null, null, null,null,null);
Osoba herb = new Osoba("Herb Powers", abraham, penelope, null, null, null,null,null);
Osoba homer = new Osoba("Homer Simpson", abraham, penelope, null, null, null,null,null);
Osoba marge = new Osoba("Marge Simpson", pan, jackie, null, null, null,null,null);
Osoba selma = new Osoba ("Selma Bouvier", pan, jackie, null, null, null,null,null);
Osoba bart = new Osoba("Bart Simpson", homer, abraham, penelope,marge, pan,jackie,null);
bart.sestavRodokmen();
System.out.println();
homer.sestavRodokmen();
}
}
public class Osoba {
private String name;
private Osoba father;
private Osoba dad_grandpa;
private Osoba dad_grandma;
private Osoba mother;
private Osoba mom_grandpa;
private Osoba mom_grandma;
private Osoba child;
public Osoba (String name, Osoba father, Osoba dad_grandpa, Osoba dad_grandma, Osoba mother, Osoba mom_grandpa, Osoba mom_grandma, Osoba child) {
this.name = name;
this.father = father;
this.dad_grandpa = dad_grandpa;
this.dad_grandma = dad_grandma;
this.mother = mother;
this.mom_grandpa = mom_grandpa;
this.mom_grandma = mom_grandma;
this.child = child;
}
private String rodokmen;
public void sestavRodokmen () {
System.out.println("Rodokmen pro osobu: " + name);
System.out.println("Name: " + name);
System.out.println("Father: "+ father);
System.out.println("Grandfather: "+ dad_grandpa);
System.out.println("Grandmother: "+ dad_grandma);
System.out.println("Mother: "+ mother);
System.out.println("Grandfather: "+ mom_grandpa);
System.out.println("Grandmother: "+ mom_grandma);
System.out.println("Child: "+ child);
rodokmen = "";
System.out.println(rodokmen);
}
@Override
public String toString () {
String a = "";
if(mother != null && father != null)
a += name + "\n" + father + "\n" + mother +"\n" +"\n" + child;
else
a += name;
return a;
}
}
</code></pre>
| 3 | 1,337 |
Unable to understand the boost::mutex error C++
|
<p>I am new to multithreading and I have used the thread pool mechanism to synchronize interactions amongst two classes.</p>
<p>While compiling i am unable to understand the error.</p>
<p>The classes are as below:</p>
<p>InstrumentProcessor.h</p>
<pre><code>1 #ifndef INSTRUMENTPROCESSOR_H
2 #define INSTRUMENTPROCESSOR_H
3
4 #include <boost/thread/thread.hpp>
5 #include <boost/thread/mutex.hpp>
6 #include <boost/algorithm/string.hpp>
7 #include <boost/lexical_cast.hpp>
8 #include "Semaphore.h"
9 #include "Instrument.h"
10 #include <queue>
11 #include <string>
12 #include <vector>
13
14
15 class InstrumentProcessor
16 {
17 public:
18 InstrumentProcessor(unsigned int const numThreads);
19 ~InstrumentProcessor();
20 bool Start();
21 bool Stop();
22 void AddLine(const std::string& LineRead); // Producer
23
24 private:
25 void Process(); // Worker Function
26 void ProcessLine(std::string& line); // Consumer
27
28 private:
29 unsigned int const numThreads_;
30 boost::mutex ProcessorMutex_;
31 boost::thread_group ProcessorGroup_;
32 Semaphore taskCount_;
33 std::queue<std::string> Line_;
34 bool stop_;
35 std::vector<std::string> elements_;
36 std::vector<Instrument> Instruments_;
37 };
38
39 #endif /* INSTRUMENTPROCESSOR_H */
</code></pre>
<p>InstrumentProcessor.cpp</p>
<pre><code>1 #include "InstrumentProcessor.h"
2
3 InstrumentProcessor::InstrumentProcessor(unsigned int const numThreads)
4 : numThreads_(numThreads), stop_(false)
5 {
6 Instruments_.reserve(25);
7 }
8
9 InstrumentProcessor::~InstrumentProcessor()
10 {
11
12 }
13
14 bool InstrumentProcessor::Start()
15 {
16 std::cout << "\nParallel Processing Started ...." << std::endl;
17 for(unsigned int i=0; i<numThreads_; i++)
18 {
19 ProcessorGroup_.create_thread(boost::bind(&InstrumentProcessor ::Process, this));
20 }
21
22 return true;
23 }
24
25 bool InstrumentProcessor::Stop()
26 {
27 stop_ = true;
28 ProcessorGroup_.join_all();
29 std::cout << "\n Parallel Processing Stopped ...." << std::endl;
30 return stop_;
31 }
32
33
34 void InstrumentProcessor::Process()
35 {
36 while(!stop_)
37 {
38 --taskCount_;
39 std::string currentLine;
40 {
41 boost::mutex::scoped_lock lock(ProcessorMutex_);
42 currentLine = Line_.front();
43 Line_.pop();
44 }
45 ProcessLine(currentLine);
46 }
47 }
48
49 void InstrumentProcessor::AddLine(const std::string& LineRead)
50 {
51 boost::mutex::scoped_lock lock(ProcessorMutex_);
52 Line_.push(LineRead);
53 ++taskCount_;
54 }
55
56 void InstrumentProcessor::ProcessLine(std::string& line)
57 {
58 boost::algorithm::split(elements_, line, boost::is_any_of("\t "), boos t::token_compress_on);
59 for(unsigned int i=1; i<elements_.size(); i++)
60 {
61 if (elements_[i].compare("nan") == 0)
62 continue;
63 else
64 {
65 double data = boost::lexical_cast<double>(elements_[i] );
66 Instruments_[i-1].CleanData(data); // This function makes a call to the Insrument Class member function
67 }
68 }
69 }
</code></pre>
<p>Instrument.h</p>
<pre><code>1 #ifndef INSTRUMENT_H
2 #define INSTRUMENT_H
3
4 #include <iostream>
5 #include <boost/thread/mutex.hpp>
6 #include <cmath>
7
8 class Instrument
9 {
10 public:
11 Instrument();
12 ~Instrument();
13 bool PopulateData(double& data);
14 bool CleanData(double& data);
15 bool PrintData();
16
17 private:
18 bool getMeanAndStandardDeviation();
19
20 private:
21 double data_;
22 int N_;
23 double Mean_;
24 double M2_;
25 double stdDev_;
26 double InitialValue_;
27 bool Init_;
28 boost::mutex InstrumentMutex_;
29 };
30
31 #endif /* INSTRUMENT_H */
</code></pre>
<p>Instrument.cpp</p>
<pre><code>1 #include "Instrument.h"
2
3 Instrument::Instrument()
4 : Init_(false), data_(0.0), Mean_(0.0), stdDev_(0.0), InitialValue_(0.0), N_(0 ), M2_(0.0)
5 {
6
7 }
8
9 Instrument::~Instrument()
10 {
11
12 }
13
14 bool Instrument::PopulateData(double& data)
15 {
16 data_ = data;
17 if(!Init_)
18 {
19 InitialValue_ = data_;
20 Init_ = true;
21 std::cout << "The initial value is: " << InitialValue_ << std: :endl;
22 }
23 return true;
24 }
25
26 /* Cleaning Part 2:
27 * Each data point will be represented as the % change from the initial value.
28 * This will then be added by 101 so as to get uniform positive value with the
29 * origin of the data shifted to init_origin + 101
30 */
31
32 bool Instrument::CleanData(double& data)
33 {
34
35 std::cout << "\nData begin inserted: " << data << std::endl;
36 boost::mutex::scoped_lock lock(InstrumentMutex_);
37 PopulateData(data);
38 data_ = ((data_-InitialValue_)/InitialValue_)*100;
39 data_ += 101;
40 getMeanAndStandardDeviation();
41 return true;
42 }
43
44 // Welford recurrence relation for tick based mean and standard deviation calc ulation
45 bool Instrument::getMeanAndStandardDeviation()
46 {
47 ++N_;
48 double delta = data_ - Mean_;
49 Mean_ += delta/N_;
50 M2_ += delta*(data_ - Mean_);
51
52 if(N_ >= 2)
53 {
54 double variance = M2_/(N_-1);
55 stdDev_ = std::sqrt(variance);
56 }
57 return true;
58 }
59
60 bool Instrument::PrintData()
61 {
62 std::cout << "\nMean: " << Mean_ << "Std Dev: " << stdDev_ << std::end l;
63 return true;
64 }
</code></pre>
<p>I am compiling the above with the following compilation line:</p>
<pre><code>g++ -std=c++11 -I /usr/lib/x86_64-linux-gnu -lboost_thread -c InstrumentProcessor.cpp
</code></pre>
<p>which yields in the below error.</p>
<pre><code>In file included from /usr/include/c++/4.8/memory:64:0,
from /usr/include/boost/config/no_tr1/memory.hpp:21,
from /usr/include/boost/smart_ptr/shared_ptr.hpp:27,
from /usr/include/boost/shared_ptr.hpp:17,
from /usr/include/boost/date_time/time_clock.hpp:17,
from /usr/include/boost/thread/thread_time.hpp:9,
from /usr/include/boost/thread/lock_types.hpp:18,
from /usr/include/boost/thread/pthread/thread_data.hpp:12,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/c++/4.8/bits/stl_construct.h: In instantiation of ‘void std::_Construct(_T1*, _Args&& ...) [with _T1 = Instrument; _Args = {Instrument}]’:
/usr/include/c++/4.8/bits/stl_uninitialized.h:75:53: required from ‘static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; bool _TrivialValueTypes = false]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:117:41: required from ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:258:63: required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; _Tp = Instrument]’
/usr/include/c++/4.8/bits/stl_vector.h:1142:29: required from ‘std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = std::move_iterator<Instrument*>; _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::pointer = Instrument*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
/usr/include/c++/4.8/bits/vector.tcc:75:70: required from ‘void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
InstrumentProcessor.cpp:6:25: required from here
/usr/include/c++/4.8/bits/stl_construct.h:75:7: error: use of deleted function ‘Instrument::Instrument(const Instrument&)’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
In file included from InstrumentProcessor.h:9:0,
from InstrumentProcessor.cpp:1:
Instrument.h:8:7: note: ‘Instrument::Instrument(const Instrument&)’ is implicitly deleted because the default definition would be ill-formed:
class Instrument
^
Instrument.h:8:7: error: use of deleted function ‘boost::mutex::mutex(const boost::mutex&)’
In file included from /usr/include/boost/thread/lock_guard.hpp:11:0,
from /usr/include/boost/thread/pthread/thread_data.hpp:11,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/boost/thread/pthread/mutex.hpp:96:9: error: declared here
BOOST_THREAD_NO_COPYABLE(mutex)
^
</code></pre>
<p>Any help on this will be appreciated.</p>
| 3 | 4,752 |
How to add Values in a UITableViewCell
|
<p>Hey there I'm new to Swift and in this Community so sorry for my stupid question. Im trying to create a little quiz app with an UILabel for the Question and a tableView for the Answers.</p>
<p>I found a solution to show the Question in the UILabel but I don't have any idea how to put the Answers in the Cell from my UITabelView.</p>
<pre><code> import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
struct Question {
var id: Int
var questionText: String
var answers: [String]
var correctAnswer: Int
}
var question1 = Question(id: 1, questionText: "Foo?", answers:["1", "2", "3", "4"], correctAnswer: 2)
var question2 = Question(id: 2, questionText: "Bar?", answers:["1", "2", "3", "4"], correctAnswer: 2)
var question3 = Question(id: 3, questionText: "Baz?", answers:["1", "2", "3", "4"], correctAnswer: 2)
@IBOutlet weak var answerView: UITableView!
@IBOutlet weak var questionLabel: UILabel!
var listITemArray:[String] = Array()
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
setupButtonn()
// answers.append("Aleks")
// answers.append("Stefan")
// answers.append("Nico")
answerView.register(UINib.init(nibName: "CheckMarkCell", bundle: nil), forCellReuseIdentifier: "CheckListIdentifier")
answerView.dataSource = self
answerView.delegate = self
questionLabel.text = question5.questionText
listITemArray.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listITemArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListIdentifier") as! CheckMarkCell
cell.answerLabel.text = listITemArray[indexPath.row]
cell.selectionStyle = .none
cell.answerButton.addTarget(self, action: #selector(checkMarkButtonClicked(sender:)), for: .touchUpInside)
return cell
}
</code></pre>
| 3 | 1,047 |
Docker-Compose: how to configure container with VPN Split-Tunnelling?
|
<p>I need the network traffic of a Docker service to pass through VPN,
and also to be able to reach other containers outside VPN from that container.</p>
<p>I'm able to get the first requirement working by configuring an <code>OpenConnect</code> service</p>
<pre><code>version: "3.8"
services:
open-connect:
container_name: open-connect
image: open-connect
build:
dockerfile: Docker/OpenConnect.Dockerfile
context: .
privileged: true
environment:
- VPN_PROTOCOL
- VPN_HOST
- VPN_PORT
- VPN_USERNAME
- VPN_PASSWORD
</code></pre>
<p>and making the traffic of the other service pass through it via <code>network_mode: container:open-connect</code></p>
<pre><code>version: "3.8"
services:
vpn-client:
container_name: vpn-client
image: vpn-client
build:
dockerfile: Docker/Busybox.Dockerfile
context: ..
network_mode: container:open-connect
service-a:
hostname: service-a
container_name: service-a
image: service-a
build:
dockerfile: Docker/Busybox.Dockerfile
context: ..
networks:
backend:
service-b:
hostname: service-b
container_name: service-b
image: service-b
build:
dockerfile: Docker/Busybox.Dockerfile
context: ..
networks:
backend:
networks:
backend:
</code></pre>
<p>The problem is that only <code>service-a</code> and <code>service-b</code> are able to ping each other.</p>
<p>From <code>vpn-client</code> it is not possible to reach neither <code>service-a</code> or <code>service-b</code>,
similarly in the reverse way.</p>
<p>I cannot combine <code>network-mode</code> and <code>networks</code> in the <code>vpn-client</code> service:</p>
<pre><code>ERROR: 'network_mode' and 'networks' cannot be combined
</code></pre>
<p>What else can be done to make the <code>vpn-client</code>, <code>service-a</code> and <code>service-b</code> mutually reachable without being all of them behind <code>VPN network</code>?</p>
<hr />
<p><strong>Update</strong></p>
<p><strong>VPN Split Tunnelling</strong></p>
<p>Based on some resources I found, the solution seems to be the
configuration of VPN with <code>split-tunnelling</code> instead of <code>full-tunneling</code>.</p>
<ul>
<li><a href="https://cybernews.com/what-is-vpn/split-tunneling/" rel="nofollow noreferrer">https://cybernews.com/what-is-vpn/split-tunneling/</a></li>
<li><a href="https://gist.github.com/stefancocora/686bbce938f27ef72649a181e7bd0158" rel="nofollow noreferrer">https://gist.github.com/stefancocora/686bbce938f27ef72649a181e7bd0158</a></li>
<li><a href="https://gist.github.com/jagtesh/5531300" rel="nofollow noreferrer">https://gist.github.com/jagtesh/5531300</a></li>
</ul>
<p>So the question becomes: how to configure VPN split-tunnelling in the <code>open-connect</code> service?</p>
| 3 | 1,104 |
`ERROR RangeError: Maximum call stack size exceeded` - not able to load the page from nested project
|
<p>I am trying to load the page from nested project, but getting error as:
<code>ERROR RangeError: Maximum call stack size exceeded</code> - any one help me here?</p>
<p>both parent and child app has the <code>app.component.html</code> with <code>router-outlet</code> - will it be an issue?</p>
<p>my project app name (ibo-platform-service):</p>
<p><code>app-routing.module</code> :</p>
<pre><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{
path: 'home', component: HomeComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>
<p><code>app.module.ts</code> :</p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
const providers = [];
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
exports: [AppRoutingModule],
providers,
bootstrap: [AppComponent]
})
export class AppModule { }
@NgModule({})
export class App1SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AppModule,
providers
};
}
}
</code></pre>
<p>my main application router module:</p>
<pre><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{
path: '', pathMatch: 'full', redirectTo: 'home'
},
{
path: 'home',
loadChildren: () => import('./../../projects/ibo-platform-service/src/app/app.module').then((m) => m.App1SharedModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>
<p>app.module.ts:</p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { App1SharedModule } from './../../projects/ibo-platform-service/src/app/app.module';
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
App1SharedModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>when i run this no page loading from nested project app. getting an error as:</p>
<pre><code>ERROR RangeError: Maximum call stack size exceeded
at InnerSubscriber._error (InnerSubscriber.js:13)
at InnerSubscriber.error (Subscriber.js:55)
at CatchSubscriber._error (Subscriber.js:75)
at CatchSubscriber.error (Subscriber.js:55)
at CatchSubscriber.error (catchError.js:32)
at MergeMapSubscriber.notifyError (OuterSubscriber.js:7)
at InnerSubscriber._error (InnerSubscriber.js:14)
at InnerSubscriber.error (Subscriber.js:55)
at CatchSubscriber._error (Subscriber.js:75)
at CatchSubscriber.error (Subscriber.js:55)
</code></pre>
<p>any one figure-out the issue?</p>
| 3 | 1,281 |
Opening modal from dropdown list to add client
|
<p>Linked to my prior post yesterday on how to have a value of a selector change the behaviour of my javascript, I run into trouble opening a modal window. </p>
<p>The idea is that if "add client" is selected from the first dropdown list, instead of dynamically populating the second dropdown list with "projects", a modal window pops-up to allow the user to add a client. </p>
<p>I have index3.php:</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'dbconnect.php';
?>
<script type="text/javascript" src="scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
if (val != "add_client")
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("projects").innerHTML=response;
}
});
}
else
{
//code to open modal below
success: function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
//code to open modal above
}
}
</script>
<?php
echo "<table>";
echo "<form action='index3.php method='post'>";
echo "<tr>";
echo "<td>";
echo "<select name='client' id='client' onchange='fetch_select(this.value);'>";
echo "<option>Name of Firm</option>";
$select = mysqli_query($Verbinding,"SELECT client FROM clients GROUP by client");
while ($row = mysqli_fetch_array($select))
{
echo '<option value="'.$row['client'].'">'.$row['client'].'</option>';
}
echo "<option value='add_client'>Add Client</option>";
echo "</select>";
echo "</td>";
echo "<td>";
echo "<select name='project' id='projects'>";
echo "<option>Select Project</option>";
echo "</select>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
echo "<div id='overlay'>";
echo "<div>";
echo "<p>Content of modal window.</p>";
echo "</div>";
echo "</div>";
?>
</code></pre>
<p>The stylesheet modal.css works and is included through dbconnect.php and contains:</p>
<p>modal.css</p>
<pre><code>#overlay {
visibility: hidden;
position: absolute;
left: 0px;
top: 0px;
width:100%;
height:100%;
text-align:center;
z-index: 1000;
}
#overlay div {
width:300px;
margin: 100px auto;
background-color: #fff;
border:1px solid #000;
padding:15px;
text-align:center;
}
</code></pre>
<p>Hope anyone can help, thanks and with kind regards, Paul</p>
| 3 | 1,204 |
SignalR Hosting on Local Area Network
|
<p>I am developing winform application. It is working on two computer. MSSQLSERVER installed on main(host) computer. The program has working on main computer with no error.</p>
<p>I have a SignalR server(Windows Forms) that host on a computer of which IP is (192.168.1.5)</p>
<p>However, when i put that ip adress, program does not work. It always works on localhost why ?</p>
<pre><code> public partial class WinFormsClient : Form
{
/// <summary>
/// This name is simply added to sent messages to identify the user; this
/// sample does not include authentication.
/// </summary>
private String UserName { get; set; }
private IHubProxy HubProxy { get; set; }
const string ServerURI = "http://localhost:1313/signalr";
private HubConnection Connection { get; set; }
internal WinFormsClient()
{
InitializeComponent();
}
private void ButtonSend_Click(object sender, EventArgs e)
{
HubProxy.Invoke("Send", UserName, TextBoxMessage.Text);
TextBoxMessage.Text = String.Empty;
TextBoxMessage.Focus();
}
/// <summary>
/// Creates and connects the hub connection and hub proxy. This method
/// is called asynchronously from SignInButton_Click.
/// </summary>
private async void ConnectAsync()
{
Connection = new HubConnection(ServerURI);
Connection.Closed += Connection_Closed;
HubProxy = Connection.CreateHubProxy("MyHub");
//Handle incoming event from server: use Invoke to write to console from SignalR's thread
HubProxy.On<string, string>("AddMessage", (name, message) =>
this.Invoke((Action)(() =>
RichTextBoxConsole.AppendText(String.Format("{0}: {1}" + Environment.NewLine, name, message))
))
);
HubProxy.On<string>("CallForReport", (message) =>
this.Invoke((Action)(() =>
RichTextBoxConsole.AppendText(String.Format("{0}" + Environment.NewLine, message))
))
);
try
{
await Connection.Start();
}
catch (HttpRequestException)
{
StatusText.Text = "Unable to connect to server: Start server before connecting clients.";
//No connection: Don't enable Send button or show chat UI
return;
}
//Activate UI
SignInPanel.Visible = false;
ChatPanel.Visible = true;
ButtonSend.Enabled = true;
TextBoxMessage.Focus();
RichTextBoxConsole.AppendText("Connected to server at " + ServerURI + Environment.NewLine);
}
/// <summary>
/// If the server is stopped, the connection will time out after 30 seconds (default), and the
/// Closed event will fire.
/// </summary>
private void Connection_Closed()
{
//Deactivate chat UI; show login UI.
this.Invoke((Action)(() => ChatPanel.Visible = false));
this.Invoke((Action)(() => ButtonSend.Enabled = false));
this.Invoke((Action)(() => StatusText.Text = "You have been disconnected."));
this.Invoke((Action)(() => SignInPanel.Visible = true));
}
private void SignInButton_Click(object sender, EventArgs e)
{
UserName = UserNameTextBox.Text;
//Connect to server (use async method to avoid blocking UI thread)
if (!String.IsNullOrEmpty(UserName))
{
StatusText.Visible = true;
StatusText.Text = "Connecting to server...";
ConnectAsync();
}
}
private void WinFormsClient_FormClosing(object sender, FormClosingEventArgs e)
{
if (Connection != null)
{
Connection.Stop();
Connection.Dispose();
}
}
}
</code></pre>
<p>I would like to change localhost to (192.168.1.5:1313)
After that, I would like to recivemessage from client to server.</p>
<p>Client 1 IP is (192.168.1.5)
Client 2 IP is (192.168.1.20)</p>
<p>SignlaR Hub + MSSQLSERVER + Client1 in the same computer.</p>
| 3 | 1,637 |
Post not working in Ajax to save the input to database
|
<p>I am trying to save an event via ajax on the full calendar.</p>
<p>I have tested the php for inserting the events and it is working fine. So I realized that the events are not being passed via ajax.</p>
<p>They are not being passed for insertion or updatation.</p>
<pre><code><script>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: "events.php",
// Convert the allDay from string to boolean
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
var url = prompt('Type Event url, if exits:');
if (title) {
var start = $.fullCalendar.moment(start);
var end = $.fullCalendar.moment(end);
$.ajax({
url: 'add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url ,
type: "POST",
success: function(json) {
alert('Added Successfully');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
eventDrop: function(event, delta) {
var start = $.fullCalendar.moment(event.start);
var end = $.fullCalendar.moment(event.end);
$.ajax({
url: 'update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
eventResize: function(event) {
var start = $.fullCalendar.moment(event.start);
var end = $.fullCalendar.moment(event.end);
$.ajax({
url: 'update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
}
});
});
</script>
</code></pre>
<p>Here is the insertion code (add_events.php)</p>
<pre><code> $title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$url = $_POST['url'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'umar', 'Umar@295');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// insert the records
$sql = "INSERT INTO evenement (title, start, end, url) VALUES (:title, :start, :end, :url)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':url'=>$url));
</code></pre>
<p>And here is the update_events for updating the event :</p>
<pre><code> /* Values received via ajax */
$id = $_POST['id'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'umar', 'Umar@295');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// update the records
$sql = "UPDATE `evenement` SET 'title'=?, 'start'=?, 'end'=? WHERE 'id'=?";
$q = $bdd->prepare($sql);
$q->execute(array($title,$start,$end,$id));
</code></pre>
<p>I would appreciate if someone could point me into understanding how to get the POST in the Ajax working or what I am doing wrong.</p>
| 3 | 1,410 |
Google maps view android.view.InflateException: Binary XML File - error inflating class fragment
|
<p>This happened overnight after finishing this piece of code which pulls coordinates (Latitude and Longitude) from an API and displaying those coordinates with Markers onto a GoogleMap. It was working fine until this morning when I decided to implement a refresh page code. Even after I removed it just to double check, the error still remains.</p>
<p>I need help to understand what is going on, and how can I solve this issue.</p>
<p>XML</p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.muhd.findtaxi.MapsActivity" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</FrameLayout>
</code></pre>
<p>MapsActivity:</p>
<pre><code>import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
JSONParser jsonParser = new JSONParser();
private GoogleMap mMap;
private GoogleMap nMap;
private static final LatLng Tampines = new LatLng(1.3525,103.9446);
List<TaxiCoordinates> myCoordinates = new ArrayList<TaxiCoordinates>();
private ProgressDialog pDialog;
MapsActivity map;
private static final String apiURL = "http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability/";
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
myCoordinates = new ArrayList<TaxiCoordinates>();
new GetCoordinates().execute();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Tampines, 10));
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
class GetCoordinates extends AsyncTask<String, String, JSONArray> {
private ProgressDialog progressDialog;
@Override
protected JSONArray doInBackground(String... params)
{
try {
JSONArray json = jsonParser.makeHttpRequest(
apiURL, "GET");
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MapsActivity.this);
progressDialog.setMessage("Loading Taxis...");
progressDialog.show();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null)
{
//loop
for(int i = 0; i < jsonArray.length(); i++)
{
try
{
JSONObject c = jsonArray.getJSONObject(i);
TaxiCoordinates temp = new TaxiCoordinates();
temp.setLatitude(c.getDouble("Latitude"));
temp.setLongitude(c.getDouble("Longitude"));
myCoordinates.add(temp);
if(progressDialog!=null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
addMarkers();
}
}
}
public void addMarkers()
{
for(TaxiCoordinates c: myCoordinates)
{
double tempLat = c.getLatitude();
double tempLong = c.getLongitude();
LatLng pos = new LatLng(tempLat, tempLong);
mMap.addMarker(new MarkerOptions()
.position(pos)
.title("Available")
.snippet("")
.icon(BitmapDescriptorFactory.defaultMarker()));
//MarkerOptions m = new MarkerOptions().title("Available").position(new LatLng(tempLat, tempLong));
//googleMap.addMarker(m);
}
}
}
</code></pre>
<p>Android Manifest:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.muhd.findtaxi">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RegisterActivity" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCqGKEImOEKNJO3e1WL2Ex7_NCUbKFD4D8" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" />
<activity android:name=".HomeActivity"></activity>
</application>
</manifest>
</code></pre>
<p>EDIT: error points to line 54 in my MapsActivity: <code>setContentView(R.layout.activity_maps);</code></p>
<p>EDIT2: LOGCAT added</p>
<pre><code>02-24 05:23:00.785 14648-14648/com.example.muhd.findtaxi D/ChimeraCfgMgr: Reading stored module config
02-24 05:23:00.867 14648-14648/com.example.muhd.findtaxi D/ChimeraCfgMgr: Loading module com.google.android.gms.maps from APK /data/user/0/com.google.android.gms/app_chimera/chimera-module-root/module-a3e4fba11e705727c59ff3116ef21fa4834b9f56/MapsModule.apk
02-24 05:23:00.868 14648-14648/com.example.muhd.findtaxi D/ChimeraModuleLdr: Loading module APK /data/user/0/com.google.android.gms/app_chimera/chimera-module-root/module-a3e4fba11e705727c59ff3116ef21fa4834b9f56/MapsModule.apk
02-24 05:23:00.875 14648-14648/com.example.muhd.findtaxi D/ChimeraFileApk: Primary ABI of requesting process is x86
02-24 05:23:00.876 14648-14648/com.example.muhd.findtaxi D/ChimeraFileApk: Classloading successful. Optimized code found.
02-24 05:23:00.893 14648-14648/com.example.muhd.findtaxi W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/chimera-module-root/module-a3e4fba11e705727c59ff3116ef21fa4834b9f56/native-libs/x86
02-24 05:23:01.097 14648-14648/com.example.muhd.findtaxi I/Google Maps Android API: Google Play services client version: 8487000
02-24 05:23:01.124 14648-14648/com.example.muhd.findtaxi I/Google Maps Android API: Google Play services package version: 8489470
02-24 05:23:01.262 14648-14659/com.example.muhd.findtaxi I/art: Background sticky concurrent mark sweep GC freed 5319(424KB) AllocSpace objects, 4(80KB) LOS objects, 12% free, 4MB/5MB, paused 14.765ms total 38.234ms
02-24 05:23:01.427 14648-14659/com.example.muhd.findtaxi I/art: Background sticky concurrent mark sweep GC freed 4766(238KB) AllocSpace objects, 0(0B) LOS objects, 4% free, 5MB/5MB, paused 6.657ms total 31.136ms
02-24 05:23:01.518 14648-14659/com.example.muhd.findtaxi I/art: Background partial concurrent mark sweep GC freed 1924(168KB) AllocSpace objects, 1(56KB) LOS objects, 39% free, 5MB/8MB, paused 5.994ms total 38.896ms
02-24 05:23:01.567 14648-14648/com.example.muhd.findtaxi W/ContextImpl: Failed to ensure /sdcard/Android/data/com.example.muhd.findtaxi/cache: java.lang.SecurityException: Invalid mkdirs path: /storage/self/primary/Android/data/com.example.muhd.findtaxi/cache
02-24 05:23:01.572 14648-14648/com.example.muhd.findtaxi D/AndroidRuntime: Shutting down VM
02-24 05:23:01.574 14648-14648/com.example.muhd.findtaxi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muhd.findtaxi, PID: 14648
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.muhd.findtaxi/com.example.muhd.findtaxi.MapsActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2166)
at com.example.muhd.findtaxi.MapsActivity.onCreate(MapsActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798..
</code></pre>
| 3 | 8,813 |
log4j 2,.17.1 upgrade issue in OWB based web application. application not coming up
|
<p>I am trying to upgrade log4j from 1.7 to 2.17.1 in my application. but my web based application unable to start.</p>
<p>although i tried my running application running on lower log4j version of 2.8.2 where application come up without any issue but in log 4j 2.9.0 and later version it doesnt comeup . any help is appreciated .</p>
<pre><code>EVERE: Exception sending context initialized event to listener instance of class [org.apache.webbeans.servlet.WebBeansConfigurationListener] org.apache.webbeans.exception.WebBeansDeploymentException: java.lang.IllegalArgumentException at org.apache.webbeans.corespi.scanner.AbstractMetaDataDiscovery.scan(AbstractMetaDataDiscovery.java:144)
</code></pre>
<hr />
<p>adding dependency tree when trying with log4j version 2.10</p>
<pre><code> [INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ tnt-applicationserver ---
[INFO] com.companu.tnt:tnt-applicationserver:war:4.11.4-1-SNAPSHOT
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.10.0:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.10.0:compile
[INFO] +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.10.0:compile
[INFO] | \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] +- org.apache.logging.log4j:log4j-jcl:jar:2.10.0:compile
[INFO] +- org.apache.logging.log4j:log4j-1.2-api:jar:2.10.0:compile
[INFO] +- com.companu.sentinel.common:sentinel-ua:jar:3.11.0-2:compile
[INFO] +- com.companu.sentinel.common:sentinel-common-circularbuffer:jar:3.11.0-2:runtime
[INFO] +- com.companu.sentinel.common:sentinel-common-core:jar:3.11.0-2:compile
[INFO] | +- com.companu:companu-tools:jar:1.3.3:compile
[INFO] | +- com.sun:tools:jar:1.8:system
[INFO] | \- jradius:jradius-client:jar:2.0.0:compile
[INFO] +- org.flywaydb:flyway-core:jar:4.0.3:compile
[INFO] +- com.oracle:ojdbc6:jar:11.2.0.4:compile
[INFO] +- commons-cli:commons-cli:jar:1.3.1:compile
[INFO] +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
[INFO] +- commons-collections:commons-collections:jar:3.2.2:compile
[INFO] +- commons-codec:commons-codec:jar:1.10:compile
[INFO] +- org.apache.commons:commons-collections4:jar:4.1:compile
[INFO] +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] | \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] +- commons-dbutils:commons-dbutils:jar:1.6:compile
[INFO] +- commons-fileupload:commons-fileupload:jar:1.3.2:compile
[INFO] +- commons-configuration:commons-configuration:jar:1.10:compile
[INFO] +- commons-io:commons-io:jar:2.4:compile
[INFO] +- commons-logging:commons-logging:jar:1.2:compile
[INFO] +- com.companu.report:companu-report-engine:jar:1.0.1:compile
[INFO] +- com.companu.ria.toolkit:ria-toolkit-tools-pojo2as3:jar:2.0:compile
[INFO] +- com.sun.xml.ws:servlet:jar:2.2.8:compile
[INFO] | +- com.sun.xml.ws:rt:jar:2.2.8:compile
[INFO] | | +- com.sun.xml.ws:policy:jar:2.3.1:compile
[INFO] | | +- com.sun.xml.bind:jaxb-impl:jar:2.2.7:compile
[INFO] | | | \- com.sun.xml.fastinfoset:FastInfoset:jar:1.2.12:compile
[INFO] | | +- org.glassfish.gmbal:gmbal-api-only:jar:3.1.0-b001:compile
[INFO] | | | \- org.glassfish.external:management-api:jar:3.0.0-b012:compile
[INFO] | | +- org.jvnet.staxex:stax-ex:jar:1.7.1:compile
[INFO] | | +- com.sun.xml.stream.buffer:streambuffer:jar:1.5.1:compile
[INFO] | | +- org.jvnet.mimepull:mimepull:jar:1.9.1:compile
[INFO] | | +- org.codehaus.woodstox:woodstox-core-asl:jar:4.1.2:runtime
[INFO] | | +- org.codehaus.woodstox:stax2-api:jar:3.1.1:runtime
[INFO] | | \- com.sun.org.apache.xml.internal:resolver:jar:20050927:compile
[INFO] | +- com.sun.xml.ws:rt-ha:jar:2.2.8:compile
[INFO] | | \- org.glassfish.ha:ha-api:jar:3.1.9:compile
[INFO] | +- javax.annotation:javax.annotation-api:jar:1.2-b03:compile
[INFO] | \- javax.jws:jsr181-api:jar:1.0-MR1:compile
[INFO] +- javax.jms:jms:jar:1.1:compile
[INFO] +- com.sun.mail:javax.mail:jar:1.5.6:compile
[INFO] +- javax.servlet:javax.servlet-api:jar:4.0.1:provided
[INFO] +- commons-lang:commons-lang:jar:2.6:compile
[INFO] +- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] +- org.apache.geronimo.specs:geronimo-annotation_1.2_spec:jar:1.0:compile
[INFO] +- org.apache.geronimo.specs:geronimo-interceptor_1.2_spec:jar:1.0:compile
[INFO] +- org.apache.geronimo.specs:geronimo-atinject_1.0_spec:jar:1.0:compile
[INFO] +- org.apache.geronimo.specs:geronimo-jcdi_1.1_spec:jar:1.0:compile
[INFO] +- org.apache.openwebbeans:openwebbeans-spi:jar:1.6.2:compile
[INFO] +- org.apache.openwebbeans:openwebbeans-impl:jar:1.6.2:compile
[INFO] | +- org.apache.xbean:xbean-finder-shaded:jar:4.3:compile
[INFO] | \- org.apache.xbean:xbean-asm5-shaded:jar:4.3:compile
[INFO] +- org.apache.openwebbeans:openwebbeans-web:jar:1.6.2:compile
[INFO] | \- org.apache.openwebbeans:openwebbeans-el22:jar:1.6.2:compile
[INFO] +- org.quartz-scheduler:quartz:jar:2.3.1:compile
[INFO] | +- com.mchange:c3p0:jar:0.9.5.3:compile
[INFO] | +- com.mchange:mchange-commons-java:jar:0.2.15:compile
[INFO] | \- com.zaxxer:HikariCP-java7:jar:2.4.13:compile
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.7.25:compile
[INFO] +- com.companu.tnt.thirdparty.org.eclipse.birt.runtime:org.eclipse.birt.runtime:jar:4.6.0-20160607:compile
[INFO] | +- org.eclipse.birt.runtime:com.ibm.icu:jar:56.1.0.v201601250100:compile
[INFO] | +- org.eclipse.birt.runtime:org.eclipse.datatools.connectivity.oda:jar:3.5.0.201603142002:compile
[INFO] | +- org.eclipse.birt.runtime:org.eclipse.datatools.connectivity.oda.consumer:jar:3.3.0.201603142002:compile
[INFO] | +- org.eclipse.birt.runtime:org.eclipse.datatools.enablement.oda.xml:jar:1.3.0.201603142002:compile
[INFO] | +- org.eclipse.birt.runtime:org.w3c.css.sac:jar:1.3.1.v200903091627:compile
[INFO] | +- org.eclipse.scout.sdk.deps:org.eclipse.core.runtime:jar:3.12.0.v20160606-1342:compile
[INFO] | | \- org.eclipse.scout.sdk.deps:org.eclipse.core.jobs:jar:3.8.0.v20160509-0411:compile (version selected from constraint [3.8.0,3.8.1))
[INFO] | +- org.eclipse.scout.sdk.deps:org.eclipse.equinox.preferences:jar:3.6.0.v20160120-1756:compile
[INFO] | +- org.eclipse.birt.runtime:org.mozilla.javascript:jar:1.7.5.v201504281450:compile
[INFO] | +- org.eclipse.scout.sdk.deps:org.eclipse.equinox.registry:jar:3.6.100.v20160223-2218:compile
[INFO] | +- org.eclipse.birt.runtime.3_7_1:org.apache.batik.util:jar:1.6.0:compile
[INFO] | +- org.eclipse.scout.sdk.deps:org.eclipse.equinox.common:jar:3.8.0.v20160509-1230:compile
[INFO] | +- org.eclipse.birt.runtime.3_7_1:org.apache.batik.css:jar:1.6.0:compile
[INFO] | +- org.eclipse.scout.sdk.deps:org.eclipse.osgi:jar:3.11.0.v20160603-1336:compile
[INFO] | +- org.eclipse.birt.runtime.3_7_1:com.lowagie.text:jar:2.1.7:compile
[INFO] | \- org.eclipse.birt.runtime.3_7_1:org.apache.xerces:jar:2.9.0:compile
[INFO] +- org.apache.poi:poi:jar:3.16:compile
[INFO] +- org.apache.poi:poi-ooxml:jar:3.16:compile
[INFO] | \- com.github.virtuald:curvesapi:jar:1.04:compile
[INFO] +- org.apache.poi:poi-ooxml-schemas:jar:3.16:compile
[INFO] +- net.sf.jtidy:jtidy:jar:r938:compile
[INFO] +- org.eclipse.jgit:org.eclipse.jgit:jar:4.11.9.201909030838-r:compile
[INFO] | +- com.jcraft:jsch:jar:0.1.54:compile
[INFO] | +- com.jcraft:jzlib:jar:1.1.1:compile
[INFO] | \- com.googlecode.javaewah:JavaEWAH:jar:1.1.6:compile
[INFO] +- org.apache.flex.blazeds:flex-messaging-common:jar:4.7.3:compile
[INFO] +- org.apache.flex.blazeds:flex-messaging-core:jar:4.7.3:compile
[INFO] +- org.apache.flex.blazeds:flex-messaging-remoting:jar:4.7.3:compile
[INFO] +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO] +- com.companu.documentation.trackandtrace:trackandtrace-en:zip:UserGuide:1.11.0-4:compile
[INFO] +- com.companu.tnt.ui:tnt-frontend-ui:zip:dist:1.8.4-1-1:compile
[INFO] +- com.companu.defence:companu-defence:jar:2.0.0-1:compile
[INFO] | +- com.google.code.findbugs:jsr305:jar:2.0.3:compile
[INFO] | +- com.fortify:fortify-annotations:jar:1.0:compile
[INFO] | \- org.apache.felix:org.osgi.core:jar:1.4.0:compile
[INFO] +- org.apache.activemq:activemq-kahadb-store:jar:5.14.1:compile
[INFO] | +- org.apache.activemq.protobuf:activemq-protobuf:jar:1.1:compile
[INFO] | \- commons-net:commons-net:jar:3.5:compile
[INFO] +- org.apache.activemq:activemq-broker:jar:5.14.1:compile
[INFO] | +- org.apache.activemq:activemq-client:jar:5.14.1:compile
[INFO] | | \- org.fusesource.hawtbuf:hawtbuf:jar:1.11:compile
[INFO] | \- org.apache.activemq:activemq-openwire-legacy:jar:5.14.1:compile
[INFO] +- org.apache.geronimo.specs:geronimo-jms_1.1_spec:jar:1.1.1:compile
[INFO] +- org.apache.geronimo.specs:geronimo-j2ee-management_1.1_spec:jar:1.0.1:compile
[INFO] +- com.google.guava:guava:jar:19.0:compile
[INFO] +- javax.ws.rs:javax.ws.rs-api:jar:2.0.1:compile
[INFO] +- org.glassfish.jersey.core:jersey-server:jar:2.22.2:compile
[INFO] | +- org.glassfish.jersey.core:jersey-common:jar:2.22.2:compile
[INFO] | | +- org.glassfish.jersey.bundles.repackaged:jersey-guava:jar:2.22.2:compile
[INFO] | | \- org.glassfish.hk2:osgi-resource-locator:jar:1.0.1:compile
[INFO] | +- org.glassfish.jersey.media:jersey-media-jaxb:jar:2.22.2:compile
[INFO] | +- org.glassfish.hk2:hk2-api:jar:2.4.0-b34:compile
[INFO] | | +- org.glassfish.hk2:hk2-utils:jar:2.4.0-b34:compile
[INFO] | | \- org.glassfish.hk2.external:aopalliance-repackaged:jar:2.4.0-b34:compile
[INFO] | +- org.glassfish.hk2.external:javax.inject:jar:2.4.0-b34:compile
[INFO] | +- org.glassfish.hk2:hk2-locator:jar:2.4.0-b34:compile
[INFO] | \- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] +- org.glassfish.jersey.containers:jersey-container-servlet:jar:2.22.2:compile
[INFO] | \- org.glassfish.jersey.containers:jersey-container-servlet-core:jar:2.22.2:compile
[INFO] +- javax.persistence:javax.persistence-api:jar:2.2:compile
[INFO] +- org.glassfish.jersey.core:jersey-client:jar:2.22.2:compile
[INFO] +- org.glassfish.jersey.ext.cdi:jersey-cdi1x:jar:2.22.2:compile
[INFO] +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar:2.9.0:compile
[INFO] | +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:jar:2.9.0:compile
[INFO] | | \- com.fasterxml.jackson.core:jackson-core:jar:2.9.0:compile
[INFO] | \- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.9.0:compile
[INFO] | \- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] +- org.apache.xmlbeans:xmlbeans:jar:2.6.0:compile
[INFO] +- dom4j:dom4j:jar:1.6.1-jboss:compile
[INFO] +- com.companu.commons.search:commons-search:jar:1.8.0-2:compile
[INFO] | \- com.fasterxml.jackson.core:jackson-databind:jar:2.7.4:compile
[INFO] +- org.antlr:antlr4-runtime:jar:4.1:runtime
[INFO] | \- org.abego.treelayout:org.abego.treelayout.core:jar:1.0.1:runtime
[INFO] +- org.apache.shiro:shiro-core:jar:1.3.2:compile
[INFO] +- org.apache.shiro:shiro-web:jar:1.3.2:compile
[INFO] +- org.apache.shiro:shiro-ehcache:jar:1.3.2:compile
[INFO] | \- net.sf.ehcache:ehcache-core:jar:2.5.3:compile
[INFO] +- com.jolbox:bonecp:jar:0.8.0.RELEASE:compile
[INFO] +- javax.xml.soap:javax.xml.soap-api:jar:1.3.5:compile
[INFO] +- javax.xml.bind:jaxb-api:jar:2.2.7:compile
[INFO] +- javax.xml.ws:jaxws-api:jar:2.2.9:compile
[INFO] +- org.apache.santuario:xmlsec:jar:1.5.8:compile
[INFO] +- org.glassfish.jersey.ext:jersey-bean-validation:jar:2.25.1:compile
[INFO] | +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] | +- javax.el:javax.el-api:jar:2.2.4:compile
[INFO] | \- org.glassfish.web:javax.el:jar:2.2.4:compile
[INFO] +- com.sun.xml.bind:jaxb-core:jar:2.2.7:compile
[INFO] | \- com.sun.istack:istack-commons-runtime:jar:2.16:compile
[INFO] +- junit:junit:jar:4.11:test
[INFO] | \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- com.companu.tools.test:test:jar:1.9.0-1:test
[INFO] | +- org.mockito:mockito-core:jar:1.9.5:test
[INFO] | +- org.hsqldb:hsqldb:jar:2.3.1:test
[INFO] | +- com.h2database:h2:jar:1.3.174:test
[INFO] | \- org.mongodb:mongo-java-driver:jar:2.11.4:test
[INFO] +- com.jayway.restassured:rest-assured:jar:2.9.0:test
[INFO] | +- org.codehaus.groovy:groovy:jar:2.4.4:test
[INFO] | +- org.codehaus.groovy:groovy-xml:jar:2.4.4:test
[INFO] | +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] | +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:test
[INFO] | +- com.jayway.restassured:json-path:jar:2.9.0:test
[INFO] | | +- org.codehaus.groovy:groovy-json:jar:2.4.4:test
[INFO] | | \- com.jayway.restassured:rest-assured-common:jar:2.9.0:test
[INFO] | \- com.jayway.restassured:xml-path:jar:2.9.0:test
[INFO] +- com.networknt:json-schema-validator:jar:0.1.2:test
[INFO] | +- org.slf4j:slf4j-ext:jar:1.7.21:test
[INFO] | | \- ch.qos.cal10n:cal10n-api:jar:0.8.1:test
[INFO] | \- io.undertow:undertow-core:jar:1.4.0.Final:test
[INFO] | +- org.jboss.xnio:xnio-api:jar:3.3.6.Final:test
[INFO] | \- org.jboss.xnio:xnio-nio:jar:3.3.6.Final:test
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.4.1:compile
[INFO] +- org.apache.httpcomponents:httpcore:jar:4.4.1:compile
[INFO] +- org.apache.httpcomponents:httpmime:jar:4.4.1:compile
[INFO] +- org.hibernate:hibernate-core:jar:5.2.18.Final:compile
[INFO] | +- org.jboss.logging:jboss-logging:jar:3.3.1.Final:compile
[INFO] | +- org.javassist:javassist:jar:3.22.0-GA:compile
[INFO] | +- antlr:antlr:jar:2.7.7:compile
[INFO] | +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.1.Final:compile
[INFO] | +- org.jboss:jandex:jar:2.0.3.Final:compile
[INFO] | +- com.fasterxml:classmate:jar:1.3.0:compile
[INFO] | +- org.dom4j:dom4j:jar:2.1.1:compile
[INFO] | \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] +- org.hibernate:hibernate-jpamodelgen:jar:5.2.18.Final:compile
[INFO] +- xmlunit:xmlunit:jar:1.4:test
[INFO] +- org.mockito:mockito-all:jar:1.9.5:test
[INFO] +- org.apache.deltaspike.core:deltaspike-core-api:jar:1.5.2:test
[INFO] +- org.apache.deltaspike.core:deltaspike-core-impl:jar:1.5.2:test
[INFO] +- org.apache.deltaspike.cdictrl:deltaspike-cdictrl-owb:jar:1.5.2:test
[INFO] | \- org.apache.deltaspike.cdictrl:deltaspike-cdictrl-api:jar:1.5.2:test
[INFO] +- org.apache.deltaspike.modules:deltaspike-test-control-module-api:jar:1.5.2:test
[INFO] +- org.apache.deltaspike.modules:deltaspike-test-control-module-impl:jar:1.5.2:test
[INFO] +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.14:test
[INFO] | \- org.apache.tomcat:tomcat-annotations-api:jar:9.0.14:test
[INFO] +- org.apache.tomcat.embed:tomcat-embed-logging-juli:jar:9.0.0.M6:test
[INFO] +- org.apache.tomcat.embed:tomcat-embed-jasper:jar:9.0.14:test
[INFO] | +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.14:test
[INFO] | \- org.eclipse.jdt:ecj:jar:3.15.0:test
[INFO] +- org.apache.tomcat:tomcat-jasper:jar:9.0.14:test
[INFO] | +- org.apache.tomcat:tomcat-servlet-api:jar:9.0.14:test
[INFO] | +- org.apache.tomcat:tomcat-juli:jar:9.0.14:test
[INFO] | +- org.apache.tomcat:tomcat-el-api:jar:9.0.14:test
[INFO] | +- org.apache.tomcat:tomcat-api:jar:9.0.14:test
[INFO] | \- org.apache.tomcat:tomcat-util-scan:jar:9.0.14:test
[INFO] | \- org.apache.tomcat:tomcat-util:jar:9.0.14:test
[INFO] +- org.apache.tomcat:tomcat-jasper-el:jar:9.0.14:test
[INFO] +- org.apache.tomcat:tomcat-jsp-api:jar:9.0.14:test
[INFO] +- org.awaitility:awaitility:jar:2.0.0:test
[INFO] | +- cglib:cglib-nodep:jar:3.1:test
[INFO] | \- org.objenesis:objenesis:jar:2.1:test
[INFO] +- com.companu.rdops.connectors.qc.notifier:qc-notifier-client:jar:1.4.1-1:test
[INFO] \- com.companu.rdops.connectors.qc.notifier:qc-notifier-shared:jar:1.4.1-1:test
[INFO] -
</code></pre>
| 3 | 7,505 |
Entity Framework Map Nested entites to View Model
|
<p>Here are my view models. The entities are exactly the same structure except the name has no ViewModel</p>
<pre><code>public class CelulaViewModel
{
public int Id { get; set; }
public string Nome { get; set; }
public int? CheckListId { get; set; }
public CheckList CheckList { get; set; }
}
public class CheckListViewModel
{
public int Id { get; set; }
public string Nome { get; set; }
public IList<CheckListGrupoViewModel> Grupos { get; set; }
public IList<CelulaViewModel> Celulas { get; set; }
}
public class CheckListGrupoViewModel
{
public int Id { get; set; }
public string Nome { get; set; }
public IList<CheckListGrupoItemViewModel> Items { get; set; }
}
public class CheckListGrupoItemViewModel
{
public int Id { get; set; }
public string Nome { get; set; }
public string Value { get; set; }
}
</code></pre>
<p>Here is my page Model</p>
<pre><code> public class IndexModel : PageModel
{
private readonly DatabaseContext _context;
public IndexModel(DatabaseContext context)
{
_context = context;
}
#region Properties
public CelulaViewModel Celula { get; set; }
#endregion
#region Handlers
public IActionResult OnGet(int? id)
{
if (id == null)
{
return NotFound();
}
Celula = _context.Celulas
.Include(c => c.CheckList)
.ThenInclude(cl => cl.Grupos)
.ThenInclude(cl => cl.Items)
.Where(c => c.Automated)
.Select(c => new CelulaViewModel
{
Id = c.Id,
Nome = c.Nome,
CheckListId = c.CheckListId,
CheckList = new CheckListViewModel
{
Id = c.CheckList.Id,
Nome = c.CheckList.Nome,
Grupos = new List<CheckListGrupoViewModel>
{
// ?? How to map the list in here?
}
}
})
.FirstOrDefault(c => c.Id == id);
if (Celula == null)
{
return NotFound();
}
return Page();
}
public IActionResult OnPost(string[] id)
{
return RedirectToPage("../Index");
}
#endregion
}
</code></pre>
<p>As you can see i'm trying to map the enty and sub entities to the view model and sub view models. The problem is when trying to do it with ICollections. I have no idea how to deal with this in lambda expression</p>
| 3 | 1,413 |
AngularJS ES6 parent function not being called by child component
|
<p>I'm a bit new to the ES6 syntax/structure of Angular 1.x, and I'm running into an issue with passing a function from a parent controller to a child controller.</p>
<p>This is how the app is tied together (I use webpack + babel with this as the entry-point):</p>
<pre><code>const requires = [
'ngRoute',
];
//App
angular.module('kanban',requires)
.controller('dashboardCtrl', dashboardCtrl)
.component('board', board)
.component('task', task)
.config(routes);
</code></pre>
<p>In my routes, I have a single route, which is my 'parent'</p>
<pre><code>export default function($routeProvider) {
$routeProvider
.when('/', {
template: dashboardTemplate,
controller: 'dashboardCtrl',
controllerAs: '$ctrl',
});
}
</code></pre>
<p>Who's controller looks like this:</p>
<pre><code>export default function($rootScope) {
$rootScope.title = 'Kanban';
let _this = this;
this.boards = [
{
_id: 'b1',
title: 'backlog',
tasks: ['t1', 't2'],
}
];
this.deleteBoard = function(board) {
console.log(board);
let index = _this.boards.indexOf(board);
if (index !== -1) {
_this.boards.splice(index, 1);
}
};
</code></pre>
<p>And in the template, the child is created with ng-repeat, passing in the function</p>
<pre><code><board ng-repeat="board in $ctrl.boards" board="board" onDelete="$ctrl.deleteBoard(board)" ></board>
</code></pre>
<p>And the board binds the attribute as a function with an &</p>
<pre><code>export const board = {
template: boardTemplate,
controller: boardCtrl,
bindings: {
board: '=',
onDelete: '&',
}
};
</code></pre>
<p>And the function is added to the controller within a different function:</p>
<pre><code>export default function boardCtrl() {
let _this = this;
this.deleteBoard = function(){
console.log(_this.onDelete);
_this.onDelete({board: _this.board});
};
}
</code></pre>
<p>And called with a click:</p>
<pre><code><button ng-click="$ctrl.deleteBoard()"></button>
</code></pre>
<p>I can reach the board (child) controller's function, which prints this in the console:</p>
<pre><code>function (locals) {
return parentGet(scope, locals);
}
</code></pre>
<p>And returns no errors, but the console.log in the parent deleteBoard function does not get called.</p>
<p>What is happening here? Why does the child seem to recognize that it is calling something in the parent scope, but is not reaching it?</p>
| 3 | 1,031 |
Using an adapter for two different situations
|
<p>I have a regular <code>RecyclerView</code> adapter that looks like this:</p>
<pre><code>public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private static final String TAG = "MessageAdapter";
private Context context;
private List<Message> messages;
public MessageAdapter(Context context, List<Message> messages) {
this.context = context;
this.messages = messages;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public Message message;
public TextView messageUser, messageText, messageTime;
public ViewHolder(View v) {
super(v);
messageUser = (TextView) v.findViewById(R.id.messageUser);
messageText = (TextView) v.findViewById(R.id.messageText);
messageTime = (TextView) v.findViewById(R.id.messageTime);
}
public void setMessage(Message message) {
this.message = message;
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.message_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Message message = messages.get(position);
holder.setMessage(message);
holder.messageUser.setText(message.getUser());
holder.messageText.setText(message.getText());
holder.messageTime.setText(message.getTime());
}
@Override
public int getItemCount() {
return messages.size();
}
}
</code></pre>
<p>I use this adapter to list all messages the user has received in the main activity.</p>
<p>In addition to this, I am using the <a href="https://github.com/bmelnychuk/AndroidTreeView" rel="nofollow noreferrer">AndroidTreeView library</a> in a different part of my app that also displays the user's messages (but in a treeview layout).</p>
<p>However, reading the documentation of this library, it says that in order to create an adapter for the treeview data, it must have the following format (taken from the docs):</p>
<pre><code>public class MyHolder extends TreeNode.BaseNodeViewHolder<IconTreeItem> {
...
@Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.layout_profile_node, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.node_value);
tvValue.setText(value.text);
return view;
}
...
public static class IconTreeItem {
public int icon;
public String text;
}
}
</code></pre>
<p>So I created a second message adapter (specifically for the AndroidTreeView library) that looks like this:</p>
<pre><code>public class MessageTreeAdapter extends TreeNode.BaseNodeViewHolder<MessageTreeAdapter.TreeItem> {
private TextView messageUser;
private TextView messageText;
private TextView messageTime;
public MessageTreeAdapter(Context context) {
super(context);
}
@Override
public View createNodeView(TreeNode node, TreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.message_layout, null, false);
Message message = value.message;
messageUser = (TextView) v.findViewById(R.id.messageUser);
messageText = (TextView) v.findViewById(R.id.messageText);
messageTime = (TextView) v.findViewById(R.id.messageTime);
messageUser.setText(message.getUser());
messageText.setText(message.getText());
messageTime.setText(message.getTime());
return view;
}
public static class TreeItem {
public Message message;
public TreeItem(Message message) {
this.message = message;
}
}
}
</code></pre>
<p>But as you can see, I'm repeating what I already have in my first adapter, <code>MessageAdapter.java</code>. I want to avoid this.</p>
<p>So my question is, how can I use a single adapter (<code>MessageAdapter.java</code>) for both situations so that I don't have to repeat any code.</p>
| 3 | 1,611 |
When setting an Adapter it Gives a Null Pointer Exception in fragment
|
<p>I am a new android learner. I ran into this null pointer exception at <code>setAdapter()</code> for lListView<code>. Both the</code>ListView` and the Adapter are NOT null.
I have attached my logcat and fragament, adapter code. I have searched the Internet, and I thought it might have something to do with Fragment. </p>
<p><strong>News_Title_fragment:</strong></p>
<pre><code>package com.example.fragmentbestpractice;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class NewsTitleFragment extends Fragment implements OnItemClickListener {
private ListView newsTitleListView;
private List<News> newsList;
private NewsAdapter adapter;
private boolean isTwoPane;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
newsList = getNews();
adapter = new NewsAdapter(activity, R.layout.news_item, newsList);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag, container, false);
newsTitleListView = (ListView) view.findViewById(R.id.news_title_list_view);
newsTitleListView.setAdapter(adapter);
newsTitleListView.setOnItemClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
News news = newsList.get(position);
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager()
.findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
NewsContentActivity.actionStart(getActivity(), news.getTitle(),
news.getContent());
}
}
private List<News> getNews() {
List<News> newsList = new ArrayList<News>();
News news1 = new News();
news1.setTitle("Succeed in College as a Learning Disabled Student");
news1.setContent("College freshmen will soon learn to live with a roommate, adjust to a new social scene and survive less-than-stellar dining hall food. Students with learning disabilities will face these transitions while also grappling with a few more hurdles.");
newsList.add(news1);
News news2 = new News();
news2.setTitle("Google Android exec poached by China's Xiaomi");
news2.setContent("China's Xiaomi has poached a key Google executive involved in the tech giant's Android phones, in a move seen as a coup for the rapidly growing Chinese smartphone maker.");
newsList.add(news2);
return newsList;
}
}
</code></pre>
<p>NewsAdapter:</p>
<pre><code>package com.example.fragmentbestpractice;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class NewsAdapter extends ArrayAdapter<News> {
private int resourceId;
public NewsAdapter(Context context, int textViewResourceId, List<News> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
News news = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
} else {
view = convertView;
}
TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);
newsTitleText.setText(news.getTitle());
return view;
}
}
</code></pre>
<p>Logcat:</p>
<pre><code> 06-30 21:45:03.099: E/AndroidRuntime(31769): FATAL EXCEPTION: main
06-30 21:45:03.099: E/AndroidRuntime(31769): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.youdianin.fragamentbestpratice/com.youdianin.fragamentbestpratice.MainActivity}: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread.access$600(ActivityThread.java:140)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1213)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.os.Handler.dispatchMessage(Handler.java:99)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.os.Looper.loop(Looper.java:137)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread.main(ActivityThread.java:4914)
06-30 21:45:03.099: E/AndroidRuntime(31769): at java.lang.reflect.Method.invokeNative(Native Method)
06-30 21:45:03.099: E/AndroidRuntime(31769): at java.lang.reflect.Method.invoke(Method.java:511)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
06-30 21:45:03.099: E/AndroidRuntime(31769): at dalvik.system.NativeStart.main(Native Method)
06-30 21:45:03.099: E/AndroidRuntime(31769): Caused by: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:774)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.rInflate(LayoutInflater.java:816)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.inflate(LayoutInflater.java:559)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.inflate(LayoutInflater.java:417)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:334)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.Activity.setContentView(Activity.java:1944)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.youdianin.fragamentbestpratice.MainActivity.onCreate(MainActivity.java:14)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.Activity.performCreate(Activity.java:5086)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.lbe.security.service.core.client.b.x.callActivityOnCreate(Unknown Source)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
06-30 21:45:03.099: E/AndroidRuntime(31769): ... 11 more
06-30 21:45:03.099: E/AndroidRuntime(31769): Caused by: java.lang.NullPointerException
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.widget.ListView.setAdapter(ListView.java:460)
06-30 21:45:03.099: E/AndroidRuntime(31769): at com.youdianin.fragamentbestpratice.NewsTitleFragment.onCreateView(NewsTitleFragment.java:51)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:807)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1013)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1112)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.app.Activity.onCreateView(Activity.java:4742)
06-30 21:45:03.099: E/AndroidRuntime(31769): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
</code></pre>
| 3 | 3,358 |
Conflict between positional_or_keyword_parameters and var_positional_parameters?
|
<p>I just defined a function in the following when I learn about the knowledge about parameter:</p>
<pre class="lang-py prettyprint-override"><code>>>> def f1(a, b, /, c=0, *args,d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'd = ', d, 'kw =', kw)
</code></pre>
<p>And it seems to be running well in my first try:</p>
<pre class="lang-py prettyprint-override"><code>>>> f1(1,2,3,*[4,5,6],d=7,e=8)
a = 1 b = 2 c = 3 args = (4, 5, 6) d = 7 kw = {'e': 8}
</code></pre>
<p>However, when I do modification about the argument for "c", which is known as positional_or_keyword_parameters in python, the running results beyond my expectation.</p>
<p>I trying to run:</p>
<pre class="lang-py prettyprint-override"><code>>>>f1(1,2,c=3,*[4,5,6],d=7,e=8)
>>>f1(1,2,*[4,5,6],d=7,e=8)
</code></pre>
<p>In my expectation, the result will be:</p>
<pre class="lang-py prettyprint-override"><code>a = 1 b = 2 c = 3 args = (4, 5, 6) d = 7 kw = {'e': 8}
a = 1 b = 2 c = 0 args = (4, 5, 6) d = 7 kw = {'e': 8}
</code></pre>
<p>But the reality is:</p>
<pre class="lang-py prettyprint-override"><code>>>> f1(1,2,c=3,*[4,5,6],d=7,e=8)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
f1(1,2,c=3,*[4,5,6],d=7,e=8)
TypeError: f1() got multiple values for argument 'c'
>>> f1(1,2,*[4,5,6],d=7,e=8)
a = 1 b = 2 c = 4 args = (5, 6) d = 7 kw = {'e': 8}
</code></pre>
<p>Then I look up the python documentation. What surprised me was that there is not any example codes in python documentation like mine. I mean, the example codes like:</p>
<pre class="lang-py prettyprint-override"><code>#the define:
def f(a, b, /, c, d, *, e, f):
def func(posonly1, posonly2, /, positional_or_keyword): ...
def func(*args, **kwargs): ...
</code></pre>
<p>In these case, the positional_or_keyword_parameters and the var_positional_parameters cannot be present at the same time.</p>
<p>Is that the truth?The syntax of python does not support that the positional_or_keyword_parameters and the var_positional_parameters present at the same time? If it does not, how can I achieve my expectations?</p>
<pre class="lang-py prettyprint-override"><code>>>> def f1(a, b, /, c=0, *args,d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'd = ', d, 'kw =', kw)
#my expectations:
>>>f1(1,2,c=3,*[4,5,6],d=7,e=8)
a = 1 b = 2 c = 3 args = (4, 5, 6) d = 7 kw = {'e': 8}
>>>
>>>f1(1,2,*[4,5,6],d=7,e=8)
a = 1 b = 2 c = 0 args = (4, 5, 6) d = 7 kw = {'e': 8}
>>>
</code></pre>
<hr />
<p>@Programmer:</p>
<p>In your answer, you gave me advice on function definition:</p>
<pre><code>def f1(a, b, /, d, *args, c=0, **kw):
</code></pre>
<p>I see that the parameter <em>d</em> is defined without a default value, but <em>d</em> is opposite. Let us talk about something more interesting about this.</p>
<p>In my opinion, the level of mastery of a syntax depends on making it useful, not just using it correctly. I would like to do a split of your codes and ignore some elements, it will like like:</p>
<pre class="lang-py prettyprint-override"><code>#define f1
def f1(a, b, /, d=0): #I prefer to do so, defining positional_or_keyword_parameters with default value
#define f2
def f2(*args,c) or def f2(*args,c=0) #define keyword_only_parameters with or without default value
</code></pre>
<p>Function definition like <em>f1</em>() is useful, think about the python function <em>range()</em>:</p>
<pre class="lang-py prettyprint-override"><code>#I assume the definition of range() is liking the following
def range(start, /, stop=None, step=1): #the dedault value is frequently used
if stop is None: #use a few tips
stop = start
start = 0
...
#I defined the positional_or_keyword_parameters(just "stop" and "step") with default value
#Therefore, I can generate the following instances:
range(10) #when I don't need the "stop" and "step", codes can be simple
range(0,10) #I need "start" and "stop" but not "step", I can still ignore the value of "step"
range(0,10,1) #I need all of them, however, I can still avoid complex syntax checks
#In short, this parameters definiton() make us more focusing on the polymorphism of functions and generating an instance by a very simple way, rather than doing complex syntax checks again and again
#Imagine this...
def range(start,/,stop=None,step): # define positional_or_keyword_parameters without default value
...
>>>range(10,step=1) #I have to write the stupid "step=1" again and again
>>>range(5,step=1)
>>>range(3,step=1)
>>>range(1,10,1) #I have to write the stupid "1" again and again
>>>range(2,5,1)
>>>range(3,6,1)
</code></pre>
<p>The situation is reversed when I define the function like <em>f2()</em>, think about the python function <em>max()</em>:</p>
<pre class="lang-py prettyprint-override"><code>#I assume the definition of max() is liking the following
def max(*args,key) or def max(*args,key=abs) :
...
#They are all useful
#In this case, max() must receive var_positional_parameters at first, and then use keyword_only_parameters("key" in this case) to achieve the polymorphism of functions. If the keyword_only_parameters without default value, it will make a serious situations that user of max() must explicitly what he/she do with the max(), and still no loss the polymorphism of functions. Relativily, the case of keyword_only_parameters with default value do more convenience but less strictness.
#example codes
max(1,2,3,4,5,6,7,8,9,10,key=abs) # *args is so long... the length of "key=abs" is easy to accept
max(*list) # It's convenient
</code></pre>
<p>Back to the main topic, my question about the definition like:</p>
<pre class="lang-py prettyprint-override"><code>def f1(a, b, /, c=0, *args,d, **kw):
...
# let us ignore irrelevant elements, it will be:
def f1(/, c=0, *args,d):
</code></pre>
<p>In fact, I loss of interest about it in few hours. The reason is that I can't figure out why I have to define a function like it. Its syntax is correct , but useless at the same time. At least I can't think of any use for it.</p>
<p>A useless syntax ...</p>
<p>Maybe my question is really boring...</p>
| 3 | 2,589 |
Binding data in angular MAT-TABLE with nested interface not working
|
<p>Trying to bind data from <strong>JSON-SERVER</strong> response into my MAT-TABLE, but getting <strong>ERROR Error: Could not find column with id "ModuleNm"</strong></p>
<p><strong>test data</strong></p>
<pre><code>{
"modules": [
{
"Id": 0,
"ModuleNm": "Visa",
"UploadDttm": "01/14/2019 21:27",
},
{
"Id": 0,
"ModuleNm": "Visa",
"UploadDttm": "01/14/2019 21:28",
},
]
</code></pre>
<p><strong>my interface</strong></p>
<pre><code>export interface IModuleType {
modules: Module[];
}
export interface Module {
Id: number;
ModuleNm: ModuleNm;
UploadDttm: string;
}
</code></pre>
<p><strong>service</strong></p>
<pre><code>loadData(selectedModuleType: string): Observable<any>{
return this._http.get<IModuleType[]>(this.testData );
}
</code></pre>
<p><strong>component</strong></p>
<pre><code>displayedColumns: string[] = ['ModuleNm', 'UploadDttm',];
dataSource!: MatTableDataSource<IModuleType>;
getData(selectedModule: string): void {
console.log('loadModuleData mothod :::::>', selectedModule);
this.test.loadData(selectedModule).subscribe({
next: (resp) => {
console.log('RESPONSE IN COMPONENT', typeof resp, resp); // getting object
this.dataSource = resp;
},
error: (err: any) => {
console.log('Errors :::>', err);
},
complete: () => {
console.log('request completed');
},
});
}
</code></pre>
<p><strong>html</strong></p>
<pre><code><table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="ModuleNm">
<th mat-header-cell *matHeaderCellDef> Type </th>
<td mat-cell *matCellDef="let element"> {{element[0].modules.ModuleNm}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code></pre>
<p>Could someone pls help me to understand why I'm getting this error?</p>
| 3 | 1,097 |
Delete method with kendo-grid using angular and sweetalert2
|
<p>My problem is that it didn't do anything after i tried to bind the data need to execute the method.
it only pops up the sweetalert but when i click both button, nothing happens.
any solution/guide for this?</p>
<p>i use an api to execute the method running in local.</p>
<p>HTML</p>
<pre><code><kendo-grid
[kendoGridBinding]="prod"
[filterable]="true"
[groupable]="true"
[sortable]="true"
[pageSize]="10"
[pageable]="true"
[height]="510">
<kendo-grid-column field="productId" title="Product ID" [width]="70"></kendo-grid-column>
<kendo-grid-column field="productName" title="Product Name" [width]="120"></kendo-grid-column>
<kendo-grid-column field="productNumber" [width]="100"></kendo-grid-column>
<kendo-grid-column field="description" [width]="130"></kendo-grid-column>
<kendo-grid-column title="command" width="100">
<ng-template kendoGridCellTemplate let-dataItem>
<button kendoGridEditCommand [primary]="true">Edit</button>
<button
[swal]="{ title: 'Delete Product',
text: 'this will delete permanently',
cancelButtonColor:'#d33',
showCancelButton:true,
cancelButtonText:'Cancel',
confirmButtonColor:'#000000',
confirmButtonText:'Delete'}"
(confirm)="deleteProduct(dataItem.productId)">
Delete
</button>
</ng-template>
</kendo-grid-column>
</kendo-grid>
</code></pre>
<p>component.ts</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
@Injectable()
export class ProductListComponent implements OnInit {
constructor(private http:HttpClient) {}
prod : any;
ngOnInit() {
this.listProduct();
}
getProduct(){
return this.http.get("http://localhost:51024/api/Product/GetAllProduct");
}
listProduct() {
this.getProduct().subscribe((data) => this.prod=data);
}
public deleteProduct(productId: number): void {
this.http.delete("http://localhost:51024/api/Product/"+productId);
}
}
</code></pre>
| 3 | 1,136 |
Receiving Promise<Void> instead of NSMutableURLRequest
|
<p>I'm attempting to login to my app, however, all my APIRequests are showing as Void instead of APIRequest. This function was working back in Swift 2 and has since gone through some minor changes to attempt to migrate from PromiseKit 4 to PromiseKit 6. </p>
<p>The function does touch a lot of other things, please leave a comment if you need to see more. The function giving me the errors is:</p>
<pre><code>class func recover403(error: Error) -> Promise<NSData> {
if case let APIError.InvalidToken(request) = error {
// Log in, then continue the promise chain
let login = RootViewController.sharedInstance.showLoginController()
return login.then { request -> Promise<NSData> in
return API.transmit(request: request as! APIRequest)
}
} else if case CocoaError.userActivityConnectionUnavailable = error {
let vc = ErrorViewController(nibName: "ErrorViewController", bundle: nil)
let actions = ["Try Again"]
vc.actions = actions
vc.promise.then { index -> Promise<NSData> in
RootViewController.sharedInstance.popAlertViewController()
return API.transmit(request: request as! APIRequest)
}.catch({ (Error) in
// No catch
})
RootViewController.sharedInstance.pushAlertViewController(nvc: vc)
vc.errorLabel.text = "Please check your network connection and try again!"
}
return Promise<NSData>(error: error)
}
</code></pre>
<p>'return API.transmit(request: request as! APIRequest)' is throwing</p>
<pre><code>Error: Value of tuple type 'Void' has no member 'value'
Warning: Cast from 'Void' to unrelated type 'APIRequest' always fails
</code></pre>
<p>the 2nd 'return API.transmit(request: request as! APIRequest)' is throwing</p>
<pre><code>Error: Generic parameter 'T' could not be inferred
Warning: Cast from '(String, Any?) -> Promise<_>' to unrelated type 'APIRequest' always fails
</code></pre>
<p>Here is the APIRequest.swift</p>
<pre><code>import Foundation
class APIRequest: NSMutableURLRequest {
var errorConditions: [APIRequestErrorCondition] = []
init(_ path: String, JSON: Any? = nil) {
let URL = NSURL(string: API.baseURL + path)!
super.init(url: URL as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
// Settings for both GET and POST
setValue(API.agent, forHTTPHeaderField: "User-Agent")
setValue("application/json", forHTTPHeaderField: "Accept")
// Settings for POST, which is assumed when JSON != nil
if let JSON = JSON {
httpMethod = "POST"
httpBody = try! JSONSerialization.data(withJSONObject: JSON, options: [])
setValue("application/json", forHTTPHeaderField: "Content-Type")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
</code></pre>
<p>And finally the transmit function:</p>
<pre><code>class func transmit(request: APIRequest) -> Promise<NSData> {
request.auth()
return Promise<NSData> { seal in
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (_data, _response, _error) in
if let data = _data {
seal.fulfill(data as NSData)
} else if let error = _error {
if case URLError.badServerResponse = error, let rsp = _response as? HTTPURLResponse {
seal.reject(BadUrlError.badResponse(rsp.statusCode))
} else {
seal.reject(error)
}
} else {
seal.reject(PMKError.invalidCallingConvention)
}
seal.fulfill(_data! as NSData)
})
task.resume()
}
}
</code></pre>
<p>This error touches a lot, so let me know in the comments if there's a section missing that you need to see!</p>
<p>Added: 'request' declaration</p>
<pre><code>class func request<T>(path: String, JSON: Any? = nil) -> Promise<T> {
let request = APIRequest(path, JSON: JSON)
request.errorConditions = [API.InvalidTokenCondition, API.BadResponseCodeCondition]
return API.promise(request: request)
}
</code></pre>
<p>Added: 'login' declaration</p>
<pre><code>func showLoginController() -> Promise<Void> {
if let vc = modalController.vcs.last as? LoginViewController {
return vc.promise
}
let vc = LoginViewController(nibName: "LoginViewController", bundle: nil)
pushModalViewController(nvc: vc, animated: true)
return vc.promise
}
</code></pre>
| 3 | 1,891 |
How can I slow down a program to make the request to the server?
|
<p>I need to know that the server is returned to display in a cell right inoformatsiya after editing or return the previous line, if an error occurs. Or I can get data asynchronously, and later to update the results of a cell?</p>
<p>The first press of the button allows the editing, the second store information on a server and object-question</p>
<pre><code>var tempText:String!
@IBAction func editButtonTapped(_ sender:UIButton) {
print("editButtonTapped")
textIsEditable = !textIsEditable
if textIsEditable == true {
tempText = questionTextView.text
questionTextView.isEditable=true
questionTextView.backgroundColor = UIColor.white
} else {
questionTextView.isEditable=false
questionTextView.backgroundColor = UIColor.clear
question.questionText=questionTextView.text
//Edit question on the server
if question.editQuestion() == true {
print("return true")
if delegate != nil {
//delegate.editQuestionAction(question: question)
delegate.editQuestionAction(cell: self)
}
} else {
questionTextView.text = tempText
question.questionText = tempText
}
}
}
</code></pre>
<p>Method in Question class for server request:</p>
<pre><code>func editQuestion() -> Bool {
var edited=false
//Prepare image for put
let stringImage:String
if questionImage == nil {
stringImage=""
} else {
stringImage=imageName
}
let editDict:[String:String] = ["category" : category,
"text" : questionText,
"image": stringImage,
"id" : questionId]
Connection.fetchData(feed: "quests", token: nil, parameters: editDict as [String : AnyObject]?, method: "PUT") { (result, responseDict) in
if let success = responseDict?["success"] as? String {
if success == "1" {
edited = true
} else {
edited = false
}
}
}
return edited
}
</code></pre>
<p>Method for request to the server:</p>
<pre><code>static func fetchData(feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:@escaping (_ success:Bool,_ data:NSDictionary?)->Void){
DispatchQueue.main.async() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//let url = NSURL(string: feed)
if let unwrapped_url = NSURL(string: serverString+feed){
let request = NSMutableURLRequest(url: unwrapped_url as URL)
if let tk = token {
let authValue = "Token \(tk)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")
}
if let parm = parameters{
do {
if let data = try JSONSerialization.data(withJSONObject: parm, options:[]) as NSData? {
//println(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil))
request.httpBody = data as Data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
}
} catch let error as NSError {
print(error)
}
}
if let unwrapped_method = method {
request.httpMethod = unwrapped_method
}
let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.timeoutIntervalForRequest = 15.0
let session = URLSession(configuration: sessionConfiguration)
let taskGetCategories = session.dataTask(with: request as URLRequest){ (responseData, response, error) -> Void in
let statusCode = (response as! HTTPURLResponse?)?.statusCode
print("Status Code: \(statusCode), error: \(error)")
if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
onCompletion(false, nil)
}
else {
do {
if let dictionary = try JSONSerialization.jsonObject(with: responseData!, options: [.mutableContainers, .allowFragments]) as? NSDictionary{
onCompletion(true,dictionary)
} else{
onCompletion(false, nil)
}
} catch let error as NSError {
print(error)
}
}
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
taskGetCategories.resume()
}
}
}
</code></pre>
<p>UPDATE(import SwiftHTTP, need ios8):</p>
<pre><code>func editQuestion(completion:@escaping (Bool)->()) {
var edited=false
//Prepare image for put
let stringImage:String
if questionImage == nil {
stringImage=""
} else {
stringImage=imageName
}
let editDict:[String:String] = ["category" : category,
"text" : questionText,
"image": stringImage,
"id" : questionId]
do {
let opt = try HTTP.PUT(serverString+"quests", parameters: editDict)
opt.start { response in
//do things...
if let err = response.error {
print("error: \(err.localizedDescription)")
DispatchQueue.main.async {
completion(edited)
}
return //also notify app of failure as needed
}
let responseDict=convertStringToDictionary(text: response.text!)
if let success = responseDict?["success"] as? String {
if success == "1" {
edited = true
completion(edited)
} else {
edited = false
completion(edited)
}
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
</code></pre>
<p>now good?</p>
| 3 | 3,603 |
Make navigation menu span length of browser
|
<p>I am trying to get my navigation menu to span the entire length of my blog. Right now it is off center to the right and a bit too short. How do I make it longer?</p>
<p>Also, you'll notice that my navigation menu is not at the very top of the page, which is where I would like it to be. How do I fix that as well?</p>
<p>And that's not it! My navigation menu is sticky, but when you scroll past it.. it gets thrown to the left side of the page. What to do?</p>
<p>Thanks in advance for your help!</p>
<p>Below is some of the code. And here is the site: <a href="http://www.studywithstyleblog.com" rel="nofollow">http://www.studywithstyleblog.com</a></p>
<pre><code><div id="navigationbar">
#cssnav {
border: 0px;
margin: 0px;
padding: 0px;
width: auto;
font: $(tabs.font); /* Template Designer - Change Font Type, Size, Etc */
color: $(tabs.text.color); /* Template Designer - Change Font Size */
}
#cssnav ul {
#cssnav ul {
background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;
_background-image: none; /* Template Designer - Change Menu Background */
height: 40px; /* Change Height of Menu */
list-style: none;
text-align: center;
margin: 0px;
padding: 0px;
}
#cssnav li {
float: none; /* none = centre */
display: inline-block;
padding: 0px;
}
#cssnav li a {
background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;
_background-image: none; /* Template Designer - Change Menu Background */
display: block;
margin: 0px;
text-align: center;
font: $(tabs.font); /* Template Designer - Change Font Type, Size, Etc */
text-decoration: none;
}
#cssnav > ul > li > a {
color: $(tabs.text.color); /* Template Designer - Change Font Color */
}
#cssnav ul ul a {
color: $(tabs.text.color); /* Template Designer - Change Color */
}
#cssnav li > a:hover, #cssnav ul li:hover {
color: $(tabs.selected.text.color); /* Template Designer - Change Font Color on Hover */
background-color: $(tabs.selected.background.color); /* Template Designer - Change Font Background on Hover */
text-decoration: none;
}
#cssnav li ul {
background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;
_background-image: none; /* Template Designer - Change Menu Background */
display: none;
height: auto;
padding: 0px;
margin: 0px;
border: -5px;
position: absolute;
width: 300px; /* Change Width Of DropDown Menu */
z-index:9999;
}
#cssnav li:hover ul {
}
#cssnav li li {
background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;
_background-image: none; /* Template Designer - Change Background */
display: block;
float: none;
margin: 0px;
padding: 0px;
width: 300px; /* Change Width Of DropDown Menu */
}
#cssnav li:hover li a {
background: #FFFFFF; /* Template Designer - Change Background of Link on Hover */
}
#cssnav li ul a {
display: block;
height: auto;
margin: 0px;
padding: 10px;
text-align: left;
}
#cssnav li ul a:hover, #cssnav li ul li:hover > a {
color: $(tabs.selected.text.color); /* Template Designer - Change Text Color on Hover */
background-color: $(tabs.selected.background.color); /* Template Designer - Change Background on Hover */
border: 0px;
text-decoration: none;
}
/*-------- Begin Drop Down Menu -------*/
</code></pre>
| 3 | 1,050 |
Drawables next to buttons?
|
<p>Ive been working on a simple app that has a feature where you can test your knowledge by answering multiple choice questions. After an answer is selected(by the radio button), i want to show either a check mark if the answer is correct, or an "X" if the answer is incorrect, to the right of the selected answer. For some reason, my code works perfectly for the first try, and then doesnt change anything when selecting other answers.</p>
<p>heres the code (its part of an adapter - child view)</p>
<pre><code> /**
* Creates the View of group(parent) in the ExpandableListView
*
* @return the View of each parent in the List
*/
@Override
public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, final ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View parentView = inflater.inflate(R.layout.custom_list_parent, parent, false);
Question myQuestion = myList.get(groupPosition);
//setting the text of each parent
TextView singleTitle = (TextView) parentView.findViewById(R.id.title);
singleTitle.setText(myQuestion.getQuestion());
//handling the indicator
ImageView indicator = (ImageView) parentView.findViewById(R.id.indicator);
//if the list is expanded use arrow up, if not then use arrow down
int imageResourceId = isExpanded ? android.R.drawable.arrow_up_float : android.R.drawable.arrow_down_float;
//initial arrow
indicator.setImageResource(imageResourceId);
indicator.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* Will expand and collapse groups depending on previous state
* @param v the View from which the ClickListener was triggered
*/
if (isExpanded) ((ExpandableListView) parent).collapseGroup(groupPosition);
else ((ExpandableListView) parent).expandGroup(groupPosition, true);
}
});
return parentView;
}
/**
* Creates the View of child in the ExpandableListView
* @return the View of each child in the List
*/
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
final View childView = inflater.inflate(R.layout.custom_list_child_questions, parent, false);
handleRadioButtons(childView,groupPosition);
return childView;
}
/**
* Checks if the child can be selected/pressed as well
*
* @return whether the child is selectable or not
*/
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
public void handleRadioButtons(View childView, int groupPosition) {
final Question myQuestion = myList.get(groupPosition);
RadioGroup group = (RadioGroup) childView.findViewById(R.id.buttonGroup);
initializeButtons(childView);
setButtonText(myQuestion);
//if one of the buttons is pressed
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
/**
* Will expand and collapse groups depending on previous state
* @param group the button group this ActionListener will operate on
* @param checkedId the ID of the individual button that was pressed
*/
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//get the index of the correct answer
int indexAnswer = Integer.parseInt(myQuestion.getAnswer()) - 1;
for (int i = 0; i < possibleAnswers.length; i++) {
//if the button at position i was pressed
if (checkedId == possibleAnswers[i].getId()) {
//if its the correct answer
if (i == indexAnswer)
possibleAnswers[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkmark, 0);
else
possibleAnswers[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.wrong, 0);
} else {
possibleAnswers[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
}
});
}
/**
* Sets the text of each radio button as a possible answer
* @param myQuestion the Question corresponding to the possible answers
*/
public void setButtonText(Question myQuestion) {
for (int i = 0; i < possibleAnswers.length; i++) {
possibleAnswers[i].setText(myQuestion.getPossibleAnswers()[i]);
}
}
/**
* Initializes the RadioButton array of possible answers
* @param childView the View in which the radio buttons are defined
*/
public void initializeButtons(View childView) {
//array of radioButtons, each button will correspond to a possible answer
possibleAnswers[0] = (RadioButton) childView.findViewById(R.id.answer1);
possibleAnswers[1] = (RadioButton) childView.findViewById(R.id.answer2);
possibleAnswers[2] = (RadioButton) childView.findViewById(R.id.answer3);
possibleAnswers[3] = (RadioButton) childView.findViewById(R.id.answer4);
}
</code></pre>
<p>}</p>
<p>and the xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#6495ED"
android:layout_width="match_parent"
android:layout_height="135dp">
</code></pre>
<p></p>
<pre><code> <RadioGroup
android:id="@+id/buttonGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice1"
android:drawablePadding="6dp"
android:textColor="#ffffff"
android:textSize="12dp"
android:id="@+id/answer1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice 2"
android:drawablePadding="6dp"
android:textColor="#ffffff"
android:textSize="12dp"
android:id="@+id/answer2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice 3"
android:drawablePadding="6dp"
android:textColor="#ffffff"
android:textSize="12dp"
android:id="@+id/answer3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choice 4"
android:drawablePadding="6dp"
android:textColor="#ffffff"
android:textSize="12dp"
android:id="@+id/answer4"
/>
</RadioGroup>
</code></pre>
<p>
</p>
<p>that's how the problem looks on the screen:
<a href="http://i.stack.imgur.com/D5ZEt.jpg" rel="nofollow">problem</a></p>
<p>Any ideas? Please help!</p>
<p><strong>EDIT:</strong></p>
<p>here's what im doing now, trying to play with visibility:</p>
<pre><code>public void handleRadioButtons(final View childView, int groupPosition) {
final Question myQuestion = myList.get(groupPosition);
RadioGroup group = (RadioGroup) childView.findViewById(R.id.buttonGroup);
initializeButtons(childView, myQuestion);
setButtonText(myQuestion);
//if one of the buttons is pressed
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
/**
* Will expand and collapse groups depending on previous state
*
* @param group the button group this ActionListener will operate on
* @param checkedId the ID of the individual button that was pressed
*/
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//get the index of the correct answer
for (int i = 0; i < possibleAnswers.length; i++) {
//if the button at position i was pressed
if (checkedId == possibleAnswers[i].getId()) {
possibleAnswers[i].getCompoundDrawables()[2].setVisible(true,true);
}
}
}
});
}
/**
* Initializes the RadioButton array of possible answers
* @param childView the View in which the radio buttons are defined
*/
public void initializeButtons(View childView,Question myQuestion) {
//array of radioButtons, each button will correspond to a possible answer
possibleAnswers[0] = (RadioButton) childView.findViewById(R.id.answer1);
possibleAnswers[1] = (RadioButton) childView.findViewById(R.id.answer2);
possibleAnswers[2] = (RadioButton) childView.findViewById(R.id.answer3);
possibleAnswers[3] = (RadioButton) childView.findViewById(R.id.answer4);
for(int i=0;i<possibleAnswers.length;i++){
if(Integer.parseInt(myQuestion.getAnswer()) - 1 == i){
possibleAnswers[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkmark, 0);
possibleAnswers[i].getCompoundDrawables()[2].setVisible(false,true);
}
else{
possibleAnswers[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.wrong, 0);
possibleAnswers[i].getCompoundDrawables()[2].setVisible(false,true);
}
}
}
</code></pre>
| 3 | 4,005 |
How to build a Docker image?
|
<p>I have a directory named docker which contains the following two files:</p>
<pre><code>docker:
|_Dockerfile
|_main.py
</code></pre>
<p><strong>The Dockerfile looks like this:</strong></p>
<pre><code>#Specifying the base image
FROM python:3.10
#here the dockerfile is pulling the python 3.10 from docker hub which already has python installed so we have all the things we need to have python in our container.
ADD main.py.
#Here we added the python file that we want to run in docker and define its location.
RUN pip install requests pygame
#Here we installed the dependencies, we are using the pygame library in our main.py file so we have to use the pip command for installing the library
CMD [ "python3" "./main.py" ]
#lastly we specified the entry command this line is simply running python ./main.py in our container terminal
</code></pre>
<p><strong>The main.py file looks like this:</strong></p>
<pre><code># Simple pygame program
# Import and initialize the pygame library
import pygame
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([500, 500])
# Running the game until the user asks to quit
running = True
while running:
# creating an if statement for the close button
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Filling the background color with a gray
screen.fill((55, 55, 55))
# Drawing a solid purple circle in the center
pygame.draw.circle(screen, (0, 0, 251), (251, 251), 74)
# Flip the display
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
</code></pre>
<p>I opened my cmd (I'm on Windows 10) and navigated to the docker directory and executed the following command:</p>
<pre><code>docker image build -t python-game .
</code></pre>
<p><strong>This is output I received</strong></p>
<pre><code>[+] Building 0.1s (2/2) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 683B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
failed to solve with frontend dockerfile.v0: failed to create LLB definition: dockerfile parse error line 5: ADD requires at least two arguments, but only one was provided. Destination could not be determined.
</code></pre>
| 3 | 1,042 |
How to add margin to nested comments?
|
<p>I am creating a Reddit clone, and right now have the ability to create comments, and sub-comments. Using CSS I was able to add a margin (indentation) to "child" comments (sub-comments). But my "grand-child" comments (sub sub-comments) retain the same level of indentation as my "child" comments. </p>
<p>How can I go about adding a logic that would increment the margin for each sub-comment? Someone suggested using sass, but i've never used it... if that's the best way to go about it, give me a hint (I want to learn). </p>
<p>This is my comment partial </p>
<pre><code><%= div_for(comment) do %>
<div class="comments_wrapper clearfix">
<div class="pull-left">
<!-- Parent Comments -->
<!-- Determines if the comment is parent or not-->
<% if !comment.ancestry? %>
<p class="parent"><%= comment.body %></p>
<p><small>Submitted <strong><%= time_ago_in_words(comment.created_at) %> ago</strong> by <%= comment.user.email %></small></p>
<!--Reply button for parent comment-->
<button onClick="$('#reply<%=comment.id%>').show()" class="btn btn-sm btn-default">Reply</button>
<!--Reply form for parent comment-->
<div id="reply<%=comment.id%>" style="display:none;">
<%= form_for [@link, @comment = Comment.new] do |f| %>
<%= f.hidden_field :ancestry, :value => comment.id %>
<%= f.text_area :body %> <br>
<%= f.submit %>
<% end %>
</div>
<% else %>
<!-- Child Comments -->
<div class="row">
<div class="col-md-3-offset-3 child">
<p class="child"><%= comment.body %></p>
<p><small>Submitted <strong>
<%= time_ago_in_words(comment.created_at) %> ago</strong> by <%= comment.user.email %></small></p>
<!--Reply button for child comment-->
<button onClick="$('#reply<%=comment.id%>').show()" class="btn btn-sm btn-default">Reply</button>
<!--Reply form for child comment-->
<div id="reply<%=comment.id%>" style="display:none;">
<%= form_for [@link, @comment = Comment.new] do |f| %>
<%= f.hidden_field :ancestry, :value => comment.id %>
<%= f.text_area :body %> <br>
<%= f.submit %>
<% end %>
</div>
</div>
</div>
<% end %>
</div>
<div class="btn-group pull-right">
<% if comment.user == current_user -%>
<%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-sm btn-default" %>
<% end %>
</div>
</div>
<% end %>
</code></pre>
<p>Lastly, this is my CSS</p>
<pre><code>@import "bootstrap-sprockets";
@import "bootstrap";
#logo {
font-size: 26px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: -1px;
padding: 15px 0;
a {
color: #2F363E;
}
}
#main_content {
#content {
float: none;
}
padding-bottom: 100px;
.link {
padding: 2em 1em;
border-bottom: 1px solid #e9e9e9;
.title {
a {
color: #FF4500;
}
}
}
.comments_title {
margin-top: 2em;
}
#comments {
.comment {
padding: 1em 0;
border-top: 1px solid #E9E9E9;
.lead {
margin-bottom: 0;
}
}
}
}
.child {
padding-left: 15%;
font-size: 20px;
}
</code></pre>
| 3 | 2,285 |
Do I need to use strict statement for this function? It's also expecting a ':' instead of a '.' for window.onload?
|
<p>Do I need to use strict statement for these functions? It's also expecting a ':' instead of a '.' for window.onload? It also says 'e' is not defined however I'm using it as an function event. Plus an unrecoverable syntax error? This is just a simple audio player for a website.</p>
<pre><code>var audio = new Audio();
var audioPlayer = {
albumId: 0,
audioTrack: 0,
currentFolder: "",
albums: [
{
artist: "Post Malone",
album: "Beerbongs & Bentleys",
folder: "Beerbongs & Bentleys",
graphic: "Beerbongs & Bentleys/b&bart.png",
songs: ["Better Now.mp3", "Psycho ft. Ty Dolla $ign.mp3", "Rockstar ft. 21 Savage.mp3"],
songTitles: ["Better Now", "Psycho ft. Ty Dolla $ign", "Rockstar ft. 21 Savage"]
}
],
selectAlbum: function(e){
console.log(audioPlayer.albumId);
$("#tracks").empty();
$("h1").text(audioPlayer.albums[audioPlayer.albumId].album);
$("#track > span").text(audioPlayer.albums[audioPlayer.albumId].songTitles[audioPlayer.audioTrack]);
$(".album_cover > img").attr("src", "albums/" + audioPlayer.albums[audioPlayer.albumId].graphic);
$("#status").text("Ready to Play");
$.each(audioPlayer.albums[audioPlayer.albumId].songTitles, function(index, item){
$("#tracks").append("<li>" + audioPlayer.albums[audioPlayer.albumId].songTitles[index] + "</li>");
});
},
playAlbum: function(){
audio.src = "../albums/" + audioPlayer.albums[audioPlayer.albumId].folder + "/" + audioPlayer.albums[audioPlayer.albumId].songs[audioPlayer.audioTrack];
audio.play();
},
changeTrack: function(direction){
console.log(direction)
if(direction === "forward" && audioPlayer.audioTrack < audioPlayer.albums[audioPlayer.albumId].songs.length - 1){
audioPlayer.audioTrack++;
}
if(direction === "back" && audioPlayer.audioTrack < audioPlayer.albums[audioPlayer.albumId].songs.length + 1){
audioPlayer.audioTrack--;
}
},
window.onload = function(){
audioPlayer.selectAlbum()
$("#status").text("Playing");
}
$(document).on("click", "#albums > div > button",
function(e){
var album = this.id.split("_");
audioPlayer.albumId = parseInt(album[1]) - 1;
audioPlayer.selectAlbum();
});
};
</code></pre>
| 3 | 1,034 |
SQL In Access, Transforming a data table into a structured data table?
|
<p>I'm using Access forms and tables for the purposes of our project. We have an Access form template that sends data to a table (Defaults) when something is changed, added or deleted on the form. The form stores the value in the "DefaultValue" and updates the table with it. Basically, it sends data to the table, updates it on-the-spot (if needed) and retrieves it afterwards to the "DefaultValue" so we can work in our forms with it.</p>
<p>That form data goes into a table [Defaults], which has 3 columns : <em>FormName, ControlName and DefaultVal</em>. Each value in a form gets categorized in the table by its [FormName] and [ControlName], both are primary key. <em>We use the same templated form with different form names multiple times. The form field names in the template are the same. [DefaultVal] has a Memo/LongText column format.</em></p>
<blockquote>
<p>Example: A row in "Defaults" reads <code>Form_Sample|Text224|Test</code>. This means there is a form named "Form_Sample" with a field named "Text224" with the DefaultValue "Test".</p>
</blockquote>
<p>So my question is, I want to pull the data from [Defaults].[DefaultVal] to the table "Analysis". The information needs to go into 7 columns (lets call them column1,2,3,4,etc due to classified company information). To define what data from column "DefaultVal" goes into one of the 7 columns in Analysis, the [ControlName] column needs to be used. Since form field names in our different forms are the same, further categorization is needed so that they don't overwrite. In order to define if the [DefaultVal] is unique, first [FormName] must be used then [ControlName] needs to be added. </p>
<blockquote>
<p>Example: If you have <code>Text224|Apple</code> from one form and <code>Text224|Orange</code> from another, they would overwrite due to the same [ControlName]. However, if we use two primary keys and have <code>Form1|Text224|Apple</code> and <code>Form2|Text224|Orange</code>, they would be unique. This is how our table defines if the value in [DefaultVal] should be overwritten or a new one should be created. The values in [DefaultVal] will change constantly and can be the same so I cannot pull the data based on that column.</p>
</blockquote>
<p>I need specific values in [DefaultVal] to be on the same row based on the [FormName] and in different columns based on the [ControlName]. <em>The table "Analysis" must be able to update information from "Defaults" and add new such.</em></p>
<p>This is how I would picture the Query:</p>
<blockquote>
<p><strong>General Functions:</strong> The query can identify if there are new rows in [Defaults] and add them according to the below logic. The query can identify if some of the values in [Defaults] have changes and updates them accordingly.</p>
<blockquote>
<p><strong>Data:</strong> Text1, Text2, Text3, Text4, Text5, Text6 and Text7 exist in [Defaults] as [ControlName]. They all have some value in [DefaultVal]. They are all part of the form "Sample" [FormName]. So their [FormName]|[ControlName]|[DefaultVal] would look like this in the columns <code>Sample|Text1|Value</code>; <code>Sample|Text2|Value2</code> etc;;; There is also another set of Text1-7 [ControlName]s, but with a different [FormName]. The values in [DefaultValue] can be the same or different.</p>
<blockquote>
<p><strong>Rule:</strong> The query knows that the [DefaultVal] value of "Text1" as a [ControlName] needs to go into [Column1] from the table [Analysis]. Text2's value goes to [Column2], Text3 into [Column3] etc.</p>
<blockquote>
<p><strong>Logic:</strong> The query takes both instances of Text1's values and wants to put them in [Column1] of [Analysis]. It seems that they have a different [FormName] so it puts them on different rows. Then it takes both instances of Text2's values, it sees that they have a different [FormName] so it wants to put them on different rows. It sees that both [FormName]s exist in Analysis and puts them on the corresponding rows.</p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
<p>I'm really sorry if this is too long, I'm guessing it is, but I don't know how to explain it otherwise. I have some basic understanding of SQL queries, but this goes way beyond my understanding and I don't even know what commands to use and where.</p>
<p>Can someone please help? =/</p>
<pre><code>INSERT INTO Analysis ([Control Name], [Control (Sub)-Section], [Control Objective], [Control Owner], [Branch Location], [Review Period], [Operating Effectiveness], [Conclusion and Recommendations])
SELECT Defaults.DefaultVal, Analysis.*
FROM Defaults as Def, Analysis as An
UNION ALL
On An.[Control Name] = Def.DefaultVal, An.[Control (Sub)-Section] = Def.DefaultVal, An.[Control Objective] = Def.DefaultVal, An.[Control Owner] = Def.DefaultVal, An.[Branch Location] = Def.DefaultVal, An.[Review Period] = Def.DefaultVal, An.[Operating Effectiveness] = Def.DefaultVal, An.[Conclusion and Recommendations] = Def.DefaultVal
PIVOT Def.FormName
WHERE NOT EXISTS
(
'SELECT *
FROM Defaults as Def
WHERE Def.ControlName = "Text684", Def.ControlName = "Text688", Def.ControlName = "Text580", Def.ControlName = "Text473", Def.ControlName = "Label548", Def.ControlName = "Label545", Def.ControlName = "Text925", Def.ControlName = "Text929"
PIVOT FormName'
)
ELSE
UPDATE Analysis
SET [Control Name], [Control (Sub)-Section], [Control Objective], [Control Owner], [Branch Location[, [Review Period], [Operating Effectiveness], [Conclusion and Recommendations] =
(
'SELECT DefaultVal
FROM Defaults
WHERE Def.ControlName = "Text684", Def.ControlName = "Text688", Def.ControlName = "Text580", Def.ControlName = "Text473", Def.ControlName = "Label548", Def.ControlName = "Label545", Def.ControlName = "Text925", Def.ControlName = "Text929"
PIVOT FormName'
)
;
</code></pre>
| 3 | 1,689 |
Knockout js devextreme longpress to open action sheet
|
<p>Hi all I have written the following code to find the <code>longpress</code> which works fine when I am not binding any data and trying gives me the right result</p>
<pre><code><div data-options="dxView : { name: 'lngPress', title: 'lngPress' } ">
<div data-options="dxContent : { targetPlaceholder: 'content' } ">
<div data-bind="event: { mousedown: function() { myFunction() },mouseleave: function() { mymouseleave() },mouseup: function() { mymouseup() } }">
Mouse over me
</div>
</div>
</code></pre>
<p></p>
<p>My Script is as follows</p>
<pre><code>var longpress = 100;
var start;
testMobileApplication.lngPress = function (params) {
var viewModel = {
myFunction: function () {
start = new Date().getTime();
},
mymouseleave: function () {
start = 0;
},
mymouseup: function () {
if (new Date().getTime() >= (start + longpress)) {
alert('long press!');
} else {
alert('short press!');
}
}
};
return viewModel;
};
</code></pre>
<p>But the same code when I bind some data this is not working as expected</p>
<pre><code><div data-options="dxView : { name: 'lngPress', title: 'lngPress' } ">
<div data-options="dxContent : { targetPlaceholder: 'content' } ">
<div data-bind="dxList: { dataSource: dataSource }" id="pr">
<div data-options="dxTemplate: { name:'item' }" data-bind="event: { mousedown: function() { myFunction() },mouseleave: function() { mymouseleave() },mouseup: function() { mymouseup() } }">
<span class="dx-field-label" data-bind="text: name"></span>
<span class="dx-field-label" data-bind="text: hire"></span>
</div>
</div>
</div>
</code></pre>
<p></p>
<p>Script is as follows</p>
<pre><code>var longpress = 100;
var start;
testMobileApplication.lngPress = function (params) {
var viewModel = {
myFunction: function () {
start = new Date().getTime();
},
mymouseleave: function () {
start = 0;
},
mymouseup: function () {
if (new Date().getTime() >= (start + longpress)) {
alert('long press!');
} else {
alert('short press!');
}
},
dataSource: [
{ id: 1, name: "Bob", hire: 2005 },
{ id: 2, name: "John", hire: 2007 },
{ id: 3, name: "Frank", hire: 2001 },
{ id: 4, name: "Robert", hire: 2007 },
]
};
return viewModel;
};
</code></pre>
<p>So can some one help me</p>
| 3 | 1,109 |
Multiple Clients Broadcasting on Same UDP Socket in C
|
<p>I am implementing some sort of auction. 5 users are connected to the same port using a UDP socket on the same address (<code>INADDR_BROADCAST</code>) and same port (<code>udp_port</code>) assigned previously by <code>server.c</code>. Each of them has 10 seconds to offer a price. If 10s pass, the turn will be passed to the next person. Here is how the socket is initialized:</p>
<pre><code>udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_sockfd < 0)
error("ERROR opening socket\n");
int broadcast_en = 1, opt_en = 1;
setsockopt(udp_sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast_en, sizeof(broadcast_en)); //set broadcasting
setsockopt(udp_sockfd, SOL_SOCKET, SO_REUSEPORT, &opt_en, sizeof(opt_en));
bc_adr.sin_family = AF_INET;
bc_adr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
bc_adr.sin_port = htons(udp_port);
if (bind(udp_sockfd, (struct sockaddr *) &bc_adr, sizeof(bc_adr)) < 0)
error("ERROR on binding");
printf("I am connected to the UDP Socket now\n\n");
</code></pre>
<p>How I handle the scenario above is with <code>fd_set</code></p>
<pre><code> signal(SIGALRM, sig_handler); //Register signal handler
printf("Auction beginning...\n");
alarm(1);
int mx = -1, ans;
while (1)
{
FD_ZERO(&current_sockets);
FD_SET(udp_sockfd, &current_sockets);
FD_SET(STDIN, &current_sockets); //standard input
if ((select(udp_sockfd + 1, &current_sockets, NULL, NULL, NULL) < 0) && (turn_cnt > 5)) //max_fd is udp_sockfd
perror("ERROR on select");
if (FD_ISSET(STDIN, &current_sockets))
{
bzero(buffer, 255);
fgets(buffer, 255, stdin);
int price = atoi(buffer);
if (price > mx)
{
mx = price;
ans = turn_cnt;
}
bzero(buffer, 255);
strcat(buffer, "Person with turn ");
char c[2] = {turn_cnt + '0', '\0'};
strcat(buffer, c);
strcat(buffer, " offered price ");
char d[10]; //digits of price
int sz = 0;
while (price)
{
d[sz++] = '0' + (price % 10);
price /= 10;
}
char rd[10];
for (int i = sz - 1 ; i >= 0 ; i--)
rd[sz - 1 - i] = d[i];
rd[sz] = '\n';
rd[sz + 1] = '\0';
strcat(buffer, rd);
sendto(udp_sockfd, buffer, strlen(buffer), 0,(struct sockaddr *)&bc_adr, sizeof(struct sockaddr_in));
}
if (FD_ISSET(udp_sockfd, &current_sockets)) //something broadcasted on udp_sockfd
{
bzero(buffer, 255);
socklen_t bc_adr_len = sizeof(bc_adr);
int n = recvfrom(udp_sockfd, buffer, 255, 0, (struct sockaddr *)&bc_adr, &bc_adr_len);
if (n < 0)
error("ERROR on reading broadcasted message\n");
printf("BROADCASTED MESSAGE: %s\n", buffer);
fflush(stdout);
}
if (turn_cnt == 5)
break;
}
printf("The winner is user %d with price offer %d\n", ans, mx);
</code></pre>
<p>There weird thing happening is that, when some user broadcasts its price with some sort of message like: "Person with turn 1 offered price 11" using the <code>sendto()</code> function, this message is not received by the other clients until themselves enter their price. For example here is the terminal output of the 3rd client in the queue when he/she enters his/her price:</p>
<pre><code>I am connected to the UDP Socket now
Auction beginning...
Person number 1 in queue has 10 seconds to offer his/her price...
Time is up!
Person number 2 in queue has 10 seconds to offer his/her price...
Time is up!
Person number 3 in queue has 10 seconds to offer his/her price...
22
BROADCASTED MESSAGE: Person with turn 1 offered price 11
BROADCASTED MESSAGE: Person with turn 2 offered price 43
BROADCASTED MESSAGE: Person with turn 3 offered price 22
</code></pre>
<p>The lines starting with "BROADCASTED MESSAGE" corresponding the first and second client, are not being printed on time. They are being printed only when the third client has entered his/her offer which is 22.</p>
<p>The output terminal for the second client is like this:</p>
<pre><code>I am connected to the UDP Socket now
Auction beginning...
Person number 1 in queue has 10 seconds to offer his/her price...
Time is up!
Person number 2 in queue has 10 seconds to offer his/her price...
43
BROADCASTED MESSAGE: Person with turn 1 offered price 11
BROADCASTED MESSAGE: Person with turn 2 offered price 43
</code></pre>
<p>Again it can be seen that the first BROADCAST MESSAGE is not being printed on time.</p>
<p>I have been working on this for two days now and I seriously have no idea why isn't the <code>sendto()</code> method being detected by the other clients on-time. Could someone please help me with this? I would like to have the message (price offer) broadcasted for ALL clients simultaneously so they could see what other prices has been offered before their turn.</p>
<p><strong>Edit</strong>: I have edited some parts of my code as Remy Lebeau said in the comments:</p>
<pre><code> struct sockaddr_in bc_adr_sendto, bc_adr_recvfrom;
bc_adr_recvfrom.sin_family = AF_INET;
bc_adr_recvfrom.sin_addr.s_addr = htonl(INADDR_ANY);
bc_adr_recvfrom.sin_port = htons(udp_port);
bc_adr_sendto.sin_family = AF_INET;
bc_adr_sendto.sin_addr.s_addr = htonl(INADDR_BROADCAST);
bc_adr_sendto.sin_port = htons(udp_port);
if (bind(udp_sockfd, (struct sockaddr *) &bc_adr_recvfrom, sizeof(bc_adr_recvfrom)) < 0)
error("ERROR on binding");
...
sendto(udp_sockfd, buffer, strlen(buffer), 0,(struct sockaddr *)&bc_adr_sendto, sizeof(struct sockaddr_in));
...
socklen_t bc_adr_len = sizeof(bc_adr_recvfrom);
int n = recvfrom(udp_sockfd, buffer, 255, 0, (struct sockaddr *)&bc_adr_recvfrom, &bc_adr_len);
</code></pre>
<p>But still there is no difference in the result.</p>
<p><strong>Edit</strong>: Here is the <code>sig_handler</code> used for alarm:</p>
<pre><code>void sig_handler(int signum)
{
if (turn_cnt != 0)
printf("Time is up!\n");
printf("Person number %d in queue has 10 seconds to offer his/her price...\n", ++turn_cnt);
alarm(10);
}
</code></pre>
| 3 | 2,868 |
WebAuthn Relaying Party ID for various Setups
|
<p>I have an Angular 11 Project, which implements a WebAuthn registration. The backend is SpringBoot 2.4</p>
<p>WebAuthn Login should work in two parts of the project, the "main" and the "viewer"
The domain setup is rather complicated:</p>
<h3>Main Project</h3>
<p><em>Urls</em></p>
<ul>
<li>Local: https://localhost:4202</li>
<li>Staging: <a href="https://company.com" rel="nofollow noreferrer">https://company.com</a> (local Kubernetes Server)</li>
<li>Prod: <a href="https://company-project.com" rel="nofollow noreferrer">https://company-project.com</a></li>
</ul>
<h3>Viewer Project</h3>
<p><em>Urls</em></p>
<ul>
<li>Local: https://localhost:4200</li>
<li>Staging: <a href="https://viewer.develop.plattform.intra.company.com" rel="nofollow noreferrer">https://viewer.develop.plattform.intra.company.com</a> (local Kubernetes Server)</li>
<li>Prod: <a href="https://viewer.company-project.com" rel="nofollow noreferrer">https://viewer.company-project.com</a></li>
</ul>
<h3>Code</h3>
<p><em>environment.ts</em></p>
<pre><code>prodUrls: ['company-project.com'],
webauthn: {
name: "Company DEV",
rpId: "localhost"
}
</code></pre>
<p><em>environment.prod.ts</em> (replace in build)</p>
<pre><code>prodUrls: ['company-project.com'],
webauthn: {
name: "Company Prod",
rpId: "plattform.intra.company.com" // gets overridden by values in "prodUrls"
}
</code></pre>
<p><em>webauthn.service.ts</em></p>
<pre><code>private _getRelyingPartyInfo(): RelyingParty {
let rpId = environment.webauthn.rpId;
/**
* Check if the Hostname matches one of our Prod Hostnames
* and use this instead
*/
environment.prodUrls.forEach((url, index) => {
if (location.hostname.indexOf(url) > -1) {
rpId = environment.prodUrls[index];
}
});
const rp = {
id: rpId,
name: environment.webauthn.name
};
return rp;
}
</code></pre>
<h3>The Issues</h3>
<ul>
<li>It works locally, using the rpId <code>localhost</code> (both Backend and Frontend locally)</li>
<li>It does NOT work on staging --> Backend throws</li>
</ul>
<blockquote>
<p>WebAuthnException message: rpIdHash doesn't match the hash of preconfigured rpId.</p>
</blockquote>
<ul>
<li>It <em>should</em> work on Prod using <code>company-project.com</code> as rpId (scared to deploy as it does not work on staging)</li>
</ul>
<h3>What I tried</h3>
<p>For staging, I changed the rpId to <code>develop.plattform.intra.company.com</code> and I can register and login in "main". Logging in on "viewer" throws an error as well</p>
<p>The spec is not very specific about what should work: <a href="https://www.w3.org/TR/webauthn/#relying-party-identifier" rel="nofollow noreferrer">https://www.w3.org/TR/webauthn/#relying-party-identifier</a>, it only says what shouldn't work. I assume, that the multiple subdomains complicate things on staging?</p>
<p>What would be the correct rpId for staging and is the assumption that <code>company-project.com</code> as rpId should work on prod correct?</p>
| 3 | 1,191 |
Error on PHP Form with json decode after AJAX Request
|
<p>After much research and confusion I've decided to ask on here.</p>
<p>Basically, I can make my AJAX request post in every way except JSON. I'd like to learn it so I can just start from JSON instead of learning it down the road. </p>
<p>The <strong>PHP code</strong> below errors </p>
<blockquote>
<p>Undefined index: data</p>
</blockquote>
<p>What am I missing?</p>
<p>Here's the <strong>.serializeArray() & JSON Stringyfied</strong> console string:</p>
<pre><code>[
{
"name" : "client_id",
"value" : "111"
}, {
"name" : "project_id",
"value" : "222"
}, {
"name" : "user_id",
"value" : "465605"
}, {
"name" : "utl_latitude",
"value" : "40.6110589"
},{
"name":"utl_longitude",
"value":"-111.8999353"
},{
"name" : "utl_event",
"value":"CLOCK IN"
}, {
"name" : "utl_action",
"value" : "FOLLOW UP"
}
]
</code></pre>
<p>The <strong>AJAX request</strong> to the best of my knowledge</p>
<pre><code>// START AJAX REQUEST ---------------------------------------------------------------------------
$.ajax({
url: 'test.php',
method: 'POST',
dataType: 'json',
data: url_parameters,
//contentType: "application/json; charset=utf-8",
timeout: 5000, // Longer than 5 seconds? HTTP SERVER or PHP Offline.***
beforeSend: function () {
self.status_please_wait();
},
success: function (data, textStatus, jqXHR) {
/* PHP PDO MySQL Insert Status --------------------------------------------------
return 0 = Nothing to Update (***Disable for Select & Insert)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
// ----------------------------------------------------------------------------
// If data return 0 = Nothing to Update
// Placeholder for future mysql Update
// ----------------------------------------------------------------------------
// If data return 1 = Successful Insert Query
if (textStatus === 'success' && data === '1') {
//self.php_pdo_mysql_insert_status(data);
self.status_insert_success();
}
// ----------------------------------------------------------------------------
// If data return 2 = Database Connection refused
if (textStatus === 'success' && data === '2') {
//self.php_pdo_mysql_insert_status(data);
self.status_mysql_connection_refused();
}
// ----------------------------------------------------------------------------
// If data return 3 = MySQL Query Error OR Wrong URL Parameters
// Placeholder for future mysql error 3
// ----------------------------------------------------------------------------
},
// END SUCCESS function ---------------------------------------------------------
error: function (jqXHR, textStatus, errorThrown) {
// NIGX offline or PHP offline.
// If http server and/or PHP is/are offline...
if (errorThrown === 'timeout') {
self.status_http_php_offline();
}
}
// END ERROR function ---------------------------------------------------------
});
// END AJAX REQUEST -----------------------------------------------------------------------------
</code></pre>
<p><strong>The PHP on the server side:</strong></p>
<pre><code><?php
$decoded = json_decode($_POST['data'],true);
foreach ($decoded as $value) {
echo $value["name"] . "=" . $value["value"];
}
?>
</code></pre>
<p><strong>The PHP error</strong></p>
<blockquote>
<p><br />
<b>Notice</b>: Undefined index: data in <b>F:\Wnmp\html\mysql_post_json\test.php</b> on line <b>9</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>F:\Wnmp\html\mysql_post_json\test.php</b> on line <b>11</b><br /></p>
</blockquote>
| 3 | 1,528 |
Py_call_impl error with Tensorflow and RMSprop
|
<p>I'm attempting to run a package (via R4.0.2 - SAVERX - <a href="https://github.com/jingshuw/SAVERX" rel="nofollow noreferrer">https://github.com/jingshuw/SAVERX</a>) which uses sctransfer as a basis (<a href="https://github.com/jingshuw/sctransfer" rel="nofollow noreferrer">https://github.com/jingshuw/sctransfer</a>). And I'm running into this error regarding <code>rmsprop</code>:</p>
<pre><code>[1] "Use a pretrained model: No"
[1] "Processed file saved as: 1596347497.19716/tmpdata.rds"
[1] "Data preprocessed ..."
2020-08-02 08:51:45.539119: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10.1: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib/R/lib:/usr/lib/x86_64-linux-gnu:/usr/lib/jvm/default-java/lib/server
2020-08-02 08:51:45.539149: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
//usr/local/lib/python3.8/dist-packages/scanpy/api/__init__.py:3: FutureWarning:
In a future version of Scanpy, `scanpy.api` will be removed.
Simply use `import scanpy as sc` and `import scanpy.external as sce` instead.
warnings.warn(
[1] "Python module sctransfer imported ..."
[1] "Cross-validation round: 1"
2020-08-02 08:51:48.615482: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib/R/lib:/usr/lib/x86_64-linux-gnu:/usr/lib/jvm/default-java/lib/server
2020-08-02 08:51:48.615506: W tensorflow/stream_executor/cuda/cuda_driver.cc:312] failed call to cuInit: UNKNOWN ERROR (303)
2020-08-02 08:51:48.615521: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (TJC-Ubuntu): /proc/driver/nvidia/version does not exist
2020-08-02 08:51:48.615698: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-08-02 08:51:48.621149: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 1999965000 Hz
2020-08-02 08:51:48.621392: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55b0b3ac1b60 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-08-02 08:51:48.621406: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
Error in py_call_impl(callable, dots$args, dots$keywords) :
KeyError: 'rmsprop'
Detailed traceback:
File "//usr/local/lib/python3.8/dist-packages/sctransfer/api.py", line 84, in autoencode
loss = train(adata[adata.obs.DCA_split == 'train'],
File "//usr/local/lib/python3.8/dist-packages/sctransfer/train.py", line 46, in train
optimizer = opt.__dict__[optimizer](clipvalue=clip_grad)
Timing stopped at: 1.494 0.035 1.501
</code></pre>
<p>Is there any obvious way to debug this or fix this without waiting on author response?</p>
| 3 | 1,244 |
WSO2 VFS FTP Proxy does not read parameters
|
<p>I have written a proxy service and deployed on WSO2 ESB 5 to receive some file content via http and use vfs transport to transfer that content to an ftp server. The service works as expected when I specify the connection parameters correctly but when I specify something wrong on the connection string to simulate a down server, I can not manage to control the behavior of the VFS transport using the parameters specified in [1]. What I'm looking for is to short the delay between the error occurred in VFS and the fault exception catched by Axis; </p>
<p>As you are going to see below I specify 0 retries and 0 wait time between retries but it seems the VFSTransportSender class is not able to read somehow those values because it does all the time the same number of retries and it waits the same number of seconds each time it is executed, I also changed the values and put others but the result is always the same, the server is always retrying 3 more times with 30 seconds delay between each other besides the original request before Axis is able to receive some information related to the error.</p>
<p>Here is my proxy service that works without any issues:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="ftpProxy"
startOnLoad="true"
statistics="disable"
trace="disable"
transports="https,http">
<target>
<inSequence>
<log level="full"/>
<property expression="json-eval($.key)" name="file_name"/>
<property name="OUT_ONLY" value="true"/>
<property name="FORCE_SC_ACCEPTED" scope="axis2" value="true"/>
<property name="HTTP_SC" scope="axis2" value="200"/>
<property expression="fn:concat(get-property('file_name'), '.json')"
name="transport.vfs.ReplyFileName"
scope="transport"/>
<property name="OUT_ONLY" value="true"/>
</inSequence>
<endpoint name="ftp_endpoint">
<address uri="vfs:ftp://jairof_ftp:passftp@localhost:21">
<timeout>
<duration>2000</duration>
<responseAction>fault</responseAction>
</timeout>
<suspendOnFailure>
<errorCodes>-1</errorCodes>
<progressionFactor>1.0</progressionFactor>
</suspendOnFailure>
<markForSuspension>
<errorCodes>-1</errorCodes>
</markForSuspension>
</address>
</endpoint>
</target>
<parameter name="transport.vfs.ReconnectTimeout">0</parameter>
<parameter name="transport.vfs.MaxRetryCount">0</parameter>
<description/>
</proxy>
</code></pre>
<p>And when I want to simulate the server is not reachable I just modify the address URI and I put this one where the user is incorrect:</p>
<p><code><address uri="vfs:ftp://ja8irof_ftp:passftp@localhost:21"></code></p>
<p>I have also tried to set the transport.vfs parameters as properties before calling the endpoint but the result is exactly the same</p>
<p>Here you can inspect part of the log file where I cut some parts of the stack trace to keep the post simple:</p>
<pre><code>[2016-10-29 12:23:01,134] ERROR - VFSTransportSender cannot resolve replyFile
org.apache.commons.vfs2.FileSystemException: Could not connect to FTP server on "localhost".
... (the rest of stack trace)
...
Caused by: org.apache.commons.vfs2.FileSystemException: Could not login to FTP server on "localhost" as user "ja8irof_ftp".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:210)
... 29 more
[2016-10-29 12:23:34,223] ERROR - VFSTransportSender cannot resolve replyFile
org.apache.commons.vfs2.FileSystemException: Could not connect to FTP server on "localhost".
... (the rest of stack trace)
...
Caused by: org.apache.commons.vfs2.FileSystemException: Could not login to FTP server on "localhost" as user "ja8irof_ftp".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:210)
... 29 more
[2016-10-29 12:24:07,842] ERROR - VFSTransportSender cannot resolve replyFile
org.apache.commons.vfs2.FileSystemException: Could not connect to FTP server on "localhost".
... (the rest of stack trace)
...
Caused by: org.apache.commons.vfs2.FileSystemException: Could not login to FTP server on "localhost" as user "ja8irof_ftp".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:210)
... 29 more
[2016-10-29 12:24:07,844] ERROR - VFSTransportSender cannot resolve replyFile repeatedly: Could not connect to FTP server on "localhost".
org.apache.commons.vfs2.FileSystemException: Could not connect to FTP server on "localhost".
... (the rest of stack trace)
...
Caused by: org.apache.commons.vfs2.FileSystemException: Could not login to FTP server on "localhost" as user "ja8irof_ftp".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:210)
... 29 more
[2016-10-29 12:24:07,846] ERROR - Axis2Sender Unexpected error during sending message out
org.apache.axis2.AxisFault: cannot resolve replyFile repeatedly: Could not connect to FTP server on "localhost".
... (the rest of stack trace)
...
Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to FTP server on "localhost".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:275)
at org.apache.commons.vfs2.provider.ftp.FTPClientWrapper.createClient(FTPClientWrapper.java:100)
at org.apache.commons.vfs2.provider.ftp.FTPClientWrapper.getFtpClient(FTPClientWrapper.java:134)
at org.apache.commons.vfs2.provider.ftp.FTPClientWrapper.<init>(FTPClientWrapper.java:59)
at org.apache.commons.vfs2.provider.ftp.FtpFileProvider.doCreateFileSystem(FtpFileProvider.java:128)
at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.getFileSystem(AbstractOriginatingFileProvider.java:155)
at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:119)
at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:88)
at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:738)
at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:626)
at org.apache.synapse.transport.vfs.VFSTransportSender.writeFile(VFSTransportSender.java:233)
... 19 more
Caused by: org.apache.commons.vfs2.FileSystemException: Could not login to FTP server on "localhost" as user "ja8irof_ftp".
at org.apache.commons.vfs2.provider.ftp.FtpClientFactory.createConnection(FtpClientFactory.java:210)
... 29 more
</code></pre>
<p>Please send me any comments, suggestions... I would appreciate so much, thanks in advance for your time.</p>
<p>[1] <a href="https://docs.wso2.com/display/ESB500/VFS+Transport" rel="nofollow">https://docs.wso2.com/display/ESB500/VFS+Transport</a> </p>
| 3 | 2,549 |
JavaScript get a String from a specific charackter to a space
|
<p>i have a shoutbox and want to a username highlighting in the messages. The Shoutbox look like this:</p>
<pre><code><dl id="sbPosts">
<dt data-id="1780530" data-user="username">
<a href="user/username" class="user">username</a>
<time>00:00:00</time>
</dt>
<dd data-id="1780530" data-user="username">
@username text without highlight
</dd>
<dt data-id="1780530" data-user="username">
<a href="user/username" class="user">username</a>
<time>00:00:00</time>
</dt>
<dd data-id="1780530" data-user="username">
@username text without highlight
</dd>
<dt data-id="1780530" data-user="username">
<a href="user/username" class="user">username</a>
<time>00:00:00</time>
</dt>
<dd data-id="1780530" data-user="username">
@username text without highlight
</dd>
<dt data-id="1780530" data-user="username">
<a href="user/username" class="user">username</a>
<time>00:00:00</time>
</dt>
<dd data-id="1780530" data-user="username">
@username text without highlight
</dd>
</dl>
</code></pre>
<p>I only want to highlight the "@" and the text after this to the first space like this: "<strong>@skuhlight</strong> whats your question?"</p>
<p>In the shoutbox i want to add a span around the username like this:</p>
<pre><code><dd data-id="1780530" data-user="username">
<span class="highlight">@username</span> text without highlight
</dd>
</code></pre>
<p>Here is the code i tried...</p>
<pre><code> function highlight(username) {
var element = $('#sbPosts > dd');
var rgxp = new RegExp(username, '@');
var res = str.substr(username, ' ');
var repl = '<dd><span class="highlight">' + username + '</span>';
element.html(element.html().replace(username, repl));
}
</code></pre>
| 3 | 1,284 |
Error in formule in crystal report
|
<p>I get the following error in crystal reports:</p>
<blockquote>
<p>the remaining text does not to be part of the formule</p>
</blockquote>
<p>The error points to the last line from my formula: <code>zone;</code></p>
<p>What is wrong with the formula? Can it be done in an other way?</p>
<pre><code>stringVar zone := '';
if {?ParamPuntenboek} = 'Begin schooljaar' then
(if {LEERLING_LEERLING.LEERJAAR} = '4'then
select(toNumber({@4BTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '5'then
select(toNumber({@5BTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '6'then
select(toNumber({@6BTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';)
else
(if {?ParamPuntenboek} = 'Midden schooljaar' then
(if {LEERLING_LEERLING.LEERJAAR} = '3'then
select({@3MTOT})
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '4'then
select(toNumber({@4MTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '5'then
select(toNumber({@5MTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '6'then
select(toNumber({@6MTOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';)
else
if {?ParamPuntenboek} = 'Einde schooljaar' then
(if {LEERLING_LEERLING.LEERJAAR} = '3'then
select(toNumber({@3ETOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '4'then
select(toNumber({@4ETOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';
if {LEERLING_LEERLING.LEERJAAR} = '5'then
select(toNumber({@5ETOT}))
case '99': zone := 'A'
case '97': zone := 'A'
case '95': zone := 'A'
case '93': zone := 'A'
case '90': zone := 'A'
case '85': zone := 'A'
case '80': zone := 'A'
case '75': zone := 'A'
case '70': zone := 'B'
case '65': zone := 'B'
case '60': zone := 'B'
case '55': zone := 'B'
case '50': zone := 'B'
case '45': zone := 'C'
case '40': zone := 'C'
case '35': zone := 'C'
case '30': zone := 'C'
case '25': zone := 'C'
case '20': zone := 'D'
case '15': zone := 'D'
case '10': zone := 'E'
case '7': zone := 'E'
case '5': zone := 'E'
case '3': zone := 'E'
case '1': zone := 'E'
case '0': zone := 'E'
default: zone := '';)
)
zone;
</code></pre>
| 3 | 8,617 |
Problems with strtok()
|
<p>I have been wrestling with this for a while. I know it's a lot of code to look at, but I have no idea where the problem lies and can't seem to narrow it down. I will bounty it.</p>
<p>I wrote this class to parse bbcodes. It uses strtok() primarily, and the class works great unless you put two tags right next to each other, and I can't for the life of me figure out why.</p>
<p>For instance <code>[b] [i]test1[/i] [/b]</code> results in <code><strong> <em>test1</em> </strong></code>.
Yet <code>[b][i]test1[/i][/b]</code> results in <code><strong>i]test1/b]</strong></code>.
The last <code></strong></code> tag is only in there because the parser automatically closes tags it could not find a closing tag for in the string. It somehow misses the <code>[i]</code> and <code>[/b]</code> tags completely.</p>
<p>Here's the class as well as the one subclass it uses for setting up the various bbcodes. The subclass is basically just a data structure with no behaviours.</p>
<pre><code><?php
// beware images can contain any url/any get request. beware of csrf
class Lev_TextProcessor_Extension_BbCode {
protected $elements = array();
protected $openTags = array();
public function __construct() {
$this->elements['b'] = new Lev_TextProcessor_Extension_BbCode_Element('<strong>', '</strong>');
$this->elements['i'] = new Lev_TextProcessor_Extension_BbCode_Element('<em>', '</em>');
$this->elements['u'] = new Lev_TextProcessor_Extension_BbCode_Element('<span style="text-decoration: underline;">', '</span>');
$this->elements['s'] = new Lev_TextProcessor_Extension_BbCode_Element('<span style="text-decoration: line-through;">', '</span>');
$this->elements['size'] = new Lev_TextProcessor_Extension_BbCode_Element('<span style="font-size: ', '</span>', 'px;">');
$this->elements['color'] = new Lev_TextProcessor_Extension_BbCode_Element('<span style="color: ', '</span>', ';">');
$this->elements['center'] = new Lev_TextProcessor_Extension_BbCode_Element('<div style="text-align: center;">', '</div>', '', true, true, false);
$this->elements['url'] = new Lev_TextProcessor_Extension_BbCode_Element('<a href="', '</a>', '">');
$this->elements['email'] = new Lev_TextProcessor_Extension_BbCode_Element('<a href="mailto:', '</a>', '">');
$this->elements['img'] = new Lev_TextProcessor_Extension_BbCode_Element('<img src="', '" alt="" />', '', false, false, true);
$this->elements['youtube'] = new Lev_TextProcessor_Extension_BbCode_Element('<object width="400" height="325"><param name="movie" value="http://www.youtube.com/v/{param}"></param><embed src="http://www.youtube.com/v/', '" type="application/x-shockwave-flash" width="400" height="325"></embed></object>', '', false, false, false);
$this->elements['code'] = new Lev_TextProcessor_Extension_BbCode_Element('<pre><code>', '</code></pre>', '', true, false, false);
}
public function processText($input) {
// pre processing
$input = htmlspecialchars($input, ENT_NOQUOTES);
$input = nl2br($input);
$input = str_replace(array("\n", "\r"), '', $input);
// start main processing
$output = '';
$allow_child_tags = true;
$allow_child_quotes = true;
$string_segment = strtok($input, '[');
do {
// check content for quotes
if ($allow_child_quotes === false) {
if (strpos($string_segment, '"') === false) {
$output .= $string_segment;
}
} else {
// add content to output
$output .= $string_segment;
}
$tag_contents = strtok(']');
if (strpos($tag_contents, '/') === 0) {
// closing tag
$tag = substr($tag_contents, 1);
if (isset($this->elements[$tag]) === true && array_search($tag, $this->openTags) !== false) {
// tag found
do {
// close tags till matching tag found
$last_open_tag = array_pop($this->openTags);
$output .= $this->elements[$last_open_tag]->htmlAfter;
} while ($last_open_tag !== $tag);
$allow_child_tags = true;
$allow_child_quotes = true;
}
} else {
// opening tag
// separate tag name from argument if there is one
$equal_pos = strpos($tag_contents, '=');
if ($equal_pos === false) {
$tag_name = $tag_contents;
} else {
$tag_name = substr($tag_contents, 0, $equal_pos);
$tag_argument = substr($tag_contents, $equal_pos + 1);
}
if (isset($this->elements[$tag_name]) === true) {
// tag found
if (($this->elements[$tag_name]->allowParentTags === true || count($this->openTags) === 0) && $allow_child_tags === true) {
// add tag to open tag list and set flags
$this->openTags[] = $tag_name;
$allow_child_tags = $this->elements[$tag_name]->allowChildTags;
$allow_child_quotes = $this->elements[$tag_name]->allowChildQuotes;
$output .= $this->elements[$tag_name]->htmlBefore;
// if argument exists
if ($equal_pos !== false) {
if (strpos($tag_argument, '"') === false) {
$output .= $tag_argument;
}
$output .= $this->elements[$tag_name]->htmlCenter;
}
}
}
}
$string_segment = strtok('[');
} while ($string_segment !== false);
// close left over tags
while ($tag = array_pop($this->openTags)) {
$output .= $this->elements[$tag]->htmlAfter;
}
return $output;
}
}
?>
<?php
class Lev_TextProcessor_Extension_BbCode_Element {
public $htmlBefore;
public $htmlAfter;
public $htmlCenter;
public $allowChildQuotes;
public $allowChildTags;
public $allowParentTags;
public function __construct($html_before, $html_after, $html_center = '', $allow_child_quotes = true, $allow_child_tags = true, $allow_parent_tags = true) {
if ($allow_child_quotes === false && $allow_child_tags === true) throw new Lev_TextProcessor_Exception('You may not allow child tags if you do not allow child quotes.');
$this->htmlBefore = $html_before;
$this->htmlAfter = $html_after;
$this->htmlCenter = $html_center;
$this->allowChildQuotes = $allow_child_quotes;
$this->allowChildTags = $allow_child_tags;
$this->allowParentTags = $allow_parent_tags;
}
}
?>
</code></pre>
<p><strong>edit</strong></p>
<p>Fixed by creating the following class for tokenizing.</p>
<pre><code><?php
// unlike PHP's strtok() function, this class will not skip over empty tokens.
class Lev_TextProcessor_Tokenizer {
protected $string;
public function __construct($string) {
$this->string = $string;
}
public function getToken($token) {
$segment_length = strcspn($this->string, $token);
$token = substr($this->string, 0, $segment_length);
$this->string = substr($this->string, $segment_length + 1);
return $token;
}
}
?>
</code></pre>
| 3 | 4,221 |
add two images and one Label in TabBar, SwiftUI
|
<p>I have to implement a custom tabbar. I have attached the UI of required TabBar.</p>
<p><a href="https://i.stack.imgur.com/UKBD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UKBD8.png" alt="TabBar Image" /></a></p>
<p>I need to add two image inside the each TabBar Item. First one is above the text and second one is at bottom of text. I have tried 3 different method but each time TabBar is showing the same result.</p>
<pre><code> // method one not working
HideNavbarOf(view: HomeView())
.tabItem {
ZStack {
Image(ImageName.diamondFill.rawValue)
.resizable()
.scaledToFit()
.frame(width: 25)
Text("Subscription")
.font(.custom(Popins.regular.rawValue, size: 11))
.foregroundColor(.white)
Image(ImageName.tapSelected.rawValue)
.resizable()
.scaledToFit()
.frame(width: 25)
}
}
.tag(0)
// method two not working
HideNavbarOf(view: Text("AskQuestion"))
.tabItem {
ZStack {
Label {
Text("Shop")
.font(.custom(Popins.regular.rawValue, size: 11))
.foregroundColor(.white)
} icon: {
Image(ImageName.storeLine.rawValue)
.resizable()
.scaledToFit()
.frame(width: 10, height: 10)
}
Image(ImageName.tapSelected.rawValue)
.resizable()
.scaledToFit()
.frame(width: 10, height: 10)
}
}
.tag(1)
// method three not working
HideNavbarOf(view: Text("Chat"))
.tabItem {
Label {
Text("Home")
.font(.custom(Popins.regular.rawValue, size: 11))
.foregroundColor(.white)
} icon: {
VStack {
Image(ImageName.homeLine.rawValue)
.resizable()
.scaledToFit()
.frame(width: 10, height: 10)
Image(ImageName.tapSelected.rawValue)
.resizable()
.scaledToFit()
.frame(width: 10, height: 10)
}
}
}
.tag(2)
</code></pre>
<p>Below is the image of tabBar Item after these methods. There is no effect of any method, tabItem is only considering the first one Image and Label.</p>
<p><a href="https://i.stack.imgur.com/5E74e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5E74e.png" alt="Preview" /></a></p>
<p>How Can I achieve the required UI that have Image at top and bottom and a text in middle.</p>
| 3 | 2,184 |
How do you represent different versions of the same entity type (class) in the same UML class diagram?
|
<p>I’m trying to figure out how to model a situation with following properties:</p>
<ul>
<li>there is a set of entity types Ei...Ej and a set of relationship types between those entity types Ri...Rj in the domain;</li>
<li>one can distinguish at least two different versions of those entity and relationship types that are significant to different parts of the system <em>at the same time.</em></li>
</ul>
<p>In the simplest case, those different versions might be “real time data” version and “last approved snapshot” version. In this case, being significant to different parts of the system might translate into following:</p>
<ul>
<li>there are less privileged actors and use cases, that can only work with “last approved snapshot” version;</li>
<li>at the same time there are more privileged actors with the same or different set of use cases, that can work with “real time data ” version;</li>
<li>there are entity types Ex...Ey that either form relationships with entities ei...ej from “last approved snapshot” version or whose constraints reference values of attributes of entities ei...ej from “last approved snapshot” version;</li>
<li>at the same time there are different entity types Ea...Eb that either form relationships with entities ei...ej from “real time data” version or whose constraints reference values of attributes of entities ei...ej from “real time data” version.</li>
</ul>
<p>If I want to show all entity types Ei...Ej, Ex...Ey and Ea...Eb from aforementioned example along with their constraints and relationships between them on the same diagram, how would I do that?</p>
<p>I was thinking about using two different classes for the same entity type: one class would represent “last approved snapshot” version of that entity type and another class would represent “real time data ” version of that type.</p>
<p>But I don’t like this approach very much as</p>
<ul>
<li>it seems redundant;</li>
<li>I’m not actually sure what kind of relationship there is between two classes representing two different versions of the same entity type a how to represent that relationship in diagrams (maybe «derive» stereotype from standard profile would be appropriate here, but I'm not sure).</li>
</ul>
<hr />
<p>EDIT</p>
<p>Unfortunately, I can’t use examples from my work, so I’ve come up with this completely fictional one, but one that is also partially modeled after the problem I was trying to solve recently. I’ll be using popular “WorksInUsing” association to pay proper respects. This will make the question more concrete.</p>
<p>Also, to be clear, I’m trying to create conceptual model and not so much OOP/relational design/implementation model.</p>
<p>Let’s assume an entity type Employee.</p>
<p>Let’s assume an actor called “SkillAdministrator” managing following entity and relationship types:</p>
<ul>
<li>entity type Skill</li>
<li>entity type Department</li>
<li>relationship type KnownSkill between entity types Employee and Skill</li>
<li>relationship type WorkInDepatment between entity types Employee and Department</li>
</ul>
<p>Let’s assume, that changes in all those aforementioned entity and relationship types happen rarely but when they do they happen in very large batches and our skill administrator needs quite a time to process each such change.</p>
<p>After he’s finished processing the change, he runs PublishChange use case which creates a snapshot of entity and relationship types Skill and KnownSkill and makes that snapshot available to other users of the system.</p>
<p>Let’s now assume an actor called Manager managing following entity and relationship types:</p>
<ul>
<li>entity type Project</li>
<li>relationship type WorksInUsing between entity types Employee, Skill and Project.</li>
</ul>
<p>Only those Skills that existed at the last run of PublishChange use case can play role in WorksInUsing association. Also the pairs KnownSkill are precondition to triplets WorksInUsing, but again only those KnownSkill pairs, that existed at the last run of PublishChange use case.</p>
<p>At the same time Manager is managing WorksInUsing associations, SkillAdministrator can start working on processing the next big change in entity and relationship types that he manages. Manager doesn't see those changes, not until PublishChange use case is run again.</p>
<p>(Depending on the domain, there are multitude of different ways to handle deletion of particular skill or knownskill association by system administrator and then applying those changes - in the simplest case, both types could be assumed as permament, so new instances can be added but existing instances cannot be deleted, for examples laws work this way)</p>
| 3 | 1,175 |
How can i filter array on object in javascript
|
<p>I have an array named <code>files</code>:</p>
<pre><code> files = [
{
id: "1",
title: "aras",
price: 100,
size: 25,
tools: [
"Hammer",
"Zip",
"Line",
"Nexti"
]
},
{
id: "2",
title: "yasio",
price: 150,
size: 30,
tools: [
"Hammer",
"Zip",
]
},
{
id: "3",
title: "janio",
price: 200,
size: 30,
tools: [
"Line",
"Nexti"
]
},
{
id: "4",
title: "chashio",
price: 400,
size: 35,
tools: [
"Nexti"
]
},
]
</code></pre>
<p>I want to filter this object, for example, to get the array: prices between <code>90</code> to <code>150</code> and sizes between <code>25</code> to <code>40</code> and tools to include <code>Hammer</code> and <code>Zip</code>.
output must be:</p>
<pre><code>{id: "1", title: "aras", price: 100, size: 25,tools:[...]},
{id: "2", title: "aras", price: 150, size: 30,tools:[...]},
{id: "4", title: "aras", price: 90, size: 40,tools:[...]},
</code></pre>
<p><strong>How can i do it?</strong></p>
| 3 | 1,077 |
Failed to find the class io.confluent.connect.gcs.GcsSinkConnector while starting kafka-gcs confluent connector
|
<p>I am using confluent connector for kafka and Google Cloud Storage(GCS). I installed confluent using:</p>
<p>(I am doing this on Ubuntu 16.04 and all these commands were executed in the home directory.)</p>
<pre><code>curl https://packages.confluent.io/archive/5.0/confluent-5.0.0-2.11.tar.gz | tar xz
</code></pre>
<p>I then installed confluent-hub by:</p>
<pre><code>curl http://client.hub.confluent.io/confluent-hub-client-latest.tar.gz | tar xz
</code></pre>
<p>I then installed the kafka-GCS connector using:</p>
<pre><code>confluent-hub install confluentinc/kafka-connect-gcs:5.0.1
</code></pre>
<p>I then export the path using:</p>
<pre><code>export PATH=<insert-path-here>/confluent-5.0.0/bin:$PATH
</code></pre>
<p>I then start confluent using:</p>
<pre><code>confluent start
</code></pre>
<p>it shows:</p>
<pre><code>This CLI is intended for development only, not for production
https://docs.confluent.io/current/cli/index.html
Using CONFLUENT_CURRENT: /tmp/confluent.pc9RaNNQ
Starting zookeeper
zookeeper is [UP]
Starting kafka
kafka is [UP]
Starting schema-registry
schema-registry is [UP]
Starting kafka-rest
kafka-rest is [UP]
Starting connect
connect is [UP]
Starting ksql-server
ksql-server is [UP]
Starting control-center
control-center is [UP]
</code></pre>
<p>Checking confluent by:</p>
<pre><code>confluent status
</code></pre>
<p>gives me:</p>
<pre><code>This CLI is intended for development only, not for production
https://docs.confluent.io/current/cli/index.html
control-center is [UP]
ksql-server is [UP]
connect is [UP]
kafka-rest is [UP]
schema-registry is [UP]
kafka is [UP]
zookeeper is [UP]
</code></pre>
<p>All is fine up until now. Zookeeper and kafka are both up and running. Now when I use the following command to start the kafka-gcs confluent connector:</p>
<pre><code>confluent load gcs -d quickstart-gcs.properties
</code></pre>
<p>it gives the following error:</p>
<pre><code>Failed to find any class that implements Connector and which name
matches io.confluent.connect.gcs.GcsSinkConnector
</code></pre>
<p>The quickstart-gcs.properties file is in the home directory and looks something like this:</p>
<pre><code>name=gcs-sink
connector.class=io.confluent.connect.gcs.GcsSinkConnector
tasks.max=1
topics=test
gcs.bucket.name=test_bucket
gcs.part.size=5242880
flush.size=3
gcs.credentials.path=/path/to/kafka/key.json
storage.class=io.confluent.connect.gcs.storage.GcsStorage
format.class=io.confluent.connect.gcs.format.avro.AvroFormat
partitioner.class=io.confluent.connect.storage.partitioner
.DefaultPartitioner
schema.compatibility=NONE
confluent.topic.bootstrap.servers=localhost:9092
confluent.topic.replication.factor=1
confluent.license=
</code></pre>
<p>The line:</p>
<pre><code>partitioner.class=io.confluent.connect.storage.partitioner
.DefaultPartitioner
</code></pre>
<p>actually reads:</p>
<pre><code>partitioner.class=io.confluent.connect.storage.partitioner.DefaultPartitioner
</code></pre>
<p>I had to write it like that because of the editor limitations. Sorry for that.</p>
<p>The last line in quickstart-gcs.properties as per the <a href="https://docs.confluent.io/current/connect/kafka-connect-gcs/index.html#connect-gcs" rel="nofollow noreferrer">documentations</a> actually reads:</p>
<pre><code>confluent.license=""
</code></pre>
<p>but it did not work for me.</p>
<p>Any help here is greatly appreciated.</p>
<p><strong>EDIT 1:</strong> As per @cricket_007 comment:</p>
<pre><code>curl http://localhost:8083/connector-plugins
</code></pre>
<p>gives:</p>
<blockquote>
<p>[{"class":"io.confluent.connect.elasticsearch.ElasticsearchSinkConnector","type":"sink","version":"5.0.0"},{"class":"io.confluent.connect.hdfs.HdfsSinkConnector","type":"sink","version":"5.0.0"},{"class":"io.confluent.connect.hdfs.tools.SchemaSourceConnector","type":"source","version":"2.0.0-cp1"},{"class":"io.confluent.connect.jdbc.JdbcSinkConnector","type":"sink","version":"5.0.0"},{"class":"io.confluent.connect.jdbc.JdbcSourceConnector","type":"source","version":"5.0.0"},{"class":"io.confluent.connect.s3.S3SinkConnector","type":"sink","version":"5.0.0"},{"class":"io.confluent.connect.storage.tools.SchemaSourceConnector","type":"source","version":"2.0.0-cp1"},{"class":"org.apache.kafka.connect.file.FileStreamSinkConnector","type":"sink","version":"2.0.0-cp1"},{"class":"org.apache.kafka.connect.file.FileStreamSourceConnector","type":"source","version":"2.0.0-cp1"}]</p>
</blockquote>
| 3 | 1,698 |
Java Flat File database full of compiling errors
|
<p>There are plenty of problems as I am new, I can find spelling and such, but I can't seem to call some of the methods, and referencing some objects also doesn't seem to work. I know it's a lot of code, but this is one puzzle I can't seem to solve, and my grade depends on this. My teacher has no free to help as he is working on a coding project of his own. Please Help me!</p>
<pre><code>import java.io.*;
import java.util.Scanner;
public class FlatFileDatabase{
private final String PATH="table\\";
public boolean createTable(String file, String columns){
//create table
//allows users to specify what meta-information is in each column.
//check for hashtags.
if(!columns.startsWith("#")){
return false;
}
//check for the minimum amount of columns using String split.
if(columns.split("::").length < 2){
return false;
}
//write columns
PrintWriter pw = new PrintWriter(PATH + file);
pw.println(columns);
pw.close();
//try-catch-finally errors and exit
}
public void destroyTable(String table){
//deletes table
File f = new File(PATH + table);
f.delete();
}
public void create(String record, String file) throws IOException{
//makes method for printwriter
PrintWriter pw = new PrintWriter(new FileWriter(PATH+file,true));
pw.println(record);
pw.close();
}
public String findOne(String key, String table){
//open file
File f = new File(PATH + table);
Scanner sc = new Scanner("table.txt");
//the variables are just placeholders
String rawRecord = null;
String[] splitRecord;
String recordKey;
String record = null;
boolean recordNotFound = true;
//read each line until find record
while(recordNotFound && sc.hasNext()){
rawRecord = sc.nextLine();
splitRecord = rawRecord.split("::");
rawRecord = splitRecord[0];
if(key.equals(recordKey)){
record = recordKey;
recordNotFound = false;
}
}
//return
return record;
}
public boolean update(String key, String record, String table){
//helper variables
String contents = "";
String rawRecord;
String splitRecord[];
String recordKey;
//open
File f = new File(PATH + table);
Scanner sc = new Scanner(f);
//search for record
while(sc.hasNext()){
rawRecord = sc.nextLine();
splitRecord = rawRecord.split("::");
rawRecord = splitRecord[0];
if(key.equals(recordKey)){
contents += record;
} else {
contents += rawRecord;
}
}
f.close();
//if found, update record
//make private method of this and finding files
f.create();
//return
}
public boolean destroy(String key, String table){
//update
//return update(" ");
}
public static void main(String[]args){
createTable ct = new createTable();
destroyTable dt = new destroyTable();
findOne fo = new findOne();
update upd = new update();
Scanner sc = new Scanner(System.in);
System.out.print("What would you like to do?/n/n1]create a table/n2]delete table/n3]opentable/n4]update table");
int a = sc.nextInt();
if(a==1){
createTable();
}else if(a==2){
destroyTable();
}else if(a==3){
findOne();
}else{
update();
}
}
}
</code></pre>
| 3 | 1,457 |
Pointer Based Data Structures
|
<p>So my homework instructs me to read in a .WAV file and fill out the header and data according to their respective endians. I believe I have malloced enough memory for my header and data struct, but when I run the program, I end up with a Segmentation Fault 11. I can't seem to find where I went wrong. Any help would be appreciated!</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "prog9.h"
/*
* little_endian_2 - reads 2 bytes of little endian and reorganizes it into big endian
* INPUTS: fptr - pointer to the wav file
* OUTPUTS: none
* RETURNS: the data that is converted to big endian
*/
int little_endian_2(FILE *fptr)
{
int count;
char temp[2];
count = 0;
while (count < 2)
{
fscanf (fptr, "%s", temp);
count++;
}
char holder;
holder = temp[1];
temp[1] = temp[0];
temp[0] = holder;
printf ("%c", temp[0]);
printf("%c", temp[1]);
count = atoi(temp);
return count;
}
/*
* little_endian_4 - reads 4 bytes of little endian and reorganizes it into big endian
* INPUTS: fptr - pointer to the wav file
* OUTPUTS: none
* RETURNS: the data that is converted to big endian
*/
int little_endian_4(FILE *fptr)
{
int count = 0;
char temp[4];
while (count < 4)
{
fscanf (fptr, "%c", temp);
count++;
}
char holder;
holder = temp[3];
temp[3] = temp[0];
temp[0] = holder;
holder = temp[2];
temp[2] = temp[1];
temp[1] = holder;
count = atoi(temp);
return count;
}
/*
* read_file - read the wav file and fill out the wav file struct
* INPUTS: wavfile - a string that contains the name of the file
* OUTPUTS: none
* RETURNS: the pointer to the wav file struct created in this function
* SIDE EFFECT: prints the information stored in the wav struct
*/
WAV *read_file(char *wavfile)
{
WAV* wav_ptr = (WAV*)malloc(sizeof(WAV));
FILE *fp;
fp = fopen(wavfile,"r");
fscanf (fp, "%c", wav_ptr->RIFF); //For RIFF
wav_ptr->ChunkSize = little_endian_4(fp); //For ChunkSize
fscanf (fp, "%c", wav_ptr->WAVE); //For WAVE
fscanf (fp, "%c", wav_ptr->fmt); //For fmt
wav_ptr->Subchunk1Size = little_endian_4(fp); //for Subchunk1size
wav_ptr->AudioFormat = little_endian_2(fp); //For audioformat
wav_ptr->NumChan = little_endian_2(fp); //for numchan
wav_ptr->SamplesPerSec = little_endian_4(fp); //for samp/sec
wav_ptr->bytesPerSec = little_endian_4(fp); //for bytes/sec
wav_ptr->blockAlign = little_endian_2(fp); //for block alight
wav_ptr->bitsPerSample = little_endian_2(fp); //for bits/sample
wav_ptr->extra = (char*)malloc((wav_ptr->Subchunk1Size - 16)*sizeof(char)); //allocate memory for extra
fscanf (fp, "%c", wav_ptr->extra); //if extra
fscanf (fp, "%c", wav_ptr->Subchunk2ID); // for subchunk2id
wav_ptr->Subchunk2Size = little_endian_4(fp); //for subchunk 2
wav_ptr->data = (short int*)malloc((wav_ptr->Subchunk2Size)*sizeof(short int)); //allocate memory for data
fscanf (fp, "%hd", wav_ptr->data); //for data
return wav_ptr;
</code></pre>
| 3 | 1,386 |
Laravel - SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value
|
<p>The following is the detailed error that I am getting. I am learning to make APIs with Laravel.</p>
<p>SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'false' for column <code>upwork_task</code>.<code>products</code>.<code>show</code> at row 1 (SQL: insert into <code>pro ducts</code> (<code>catalog_id</code>, <code>image</code>, <code>name</code>, <code>size</code>, <code>size_type</code>, <code>price</code>, <code>discounted_price</code>, <code>show</code>, <code>updated_at</code>, <code>created_at</code>) values (1, <a href="https://via.placehol" rel="nofollow noreferrer">https://via.placehol</a>
der.com/640x480.png/00bbdd?text=clothes+quam, iPhone 14 Pro Max, 3191, liter, 3981, 2910, false, 2022-09-20 21:36:02, 2022-09-20 21:36:02))</p>
<p>My migration file is as follows</p>
<pre><code>Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('catalog_id');
$table->string('image');
$table->string('name');
$table->string('size');
$table->string('size_type');
$table->integer('price');
$table->integer('discounted_price')->nullable();
$table->boolean('show');
$table->timestamps();
});
</code></pre>
<p>My factory</p>
<pre><code>public function definition()
{
$show = $this->faker->randomElement(['true', 'false']);
$size_type = $this->faker->randomElement(['ml', 'liter', 'gm', 'kg', 'oz', 'lb']);
$status = $this->faker->randomElement(['Y', 'N']); //Y means there is discount, N means there is none
$price = $this->faker->numberBetween($min = 10, $max = 9999);
return [
'catalog_id' => Catalog::factory(),
'image' => $this->faker->imageUrl($width = 640, $height = 480, 'clothes'),
'name' => 'iPhone 14 Pro Max',
'size' => $this->faker->numberBetween($min = 10, $max = 5000),
'size_type' => $size_type,
'price' => $price,
'discounted_price' => $status == 'Y' ? $this->faker->numberBetween($min = $price * 0.6, $max = $price * 0.9) : null,
'show' => $show,
];
}
</code></pre>
| 3 | 1,076 |
Adding text to a list view from threads
|
<p>I am new to VB and I am trying to add text from a thread to a <code>listview</code> in my Form1.</p>
<p>I have tried implementing the <code>invokerequired</code> method but still the new text is not added to my <code>listview</code>. </p>
<p>(please see function <code>addlvDataItem</code>)</p>
<p>This what I call in my thread class:</p>
<pre><code>Private Sub DoServerListening()
'Thread to listen for new incoming socket clients
Dim mSocket As System.Net.Sockets.Socket
Dim newConnectionThread As clsTCPConnection
Dim strRemoteIPAddress As String
Do
Try
While bServerRunning = True
If mTCPListener.Pending = True Then
mSocket = mTCPListener.AcceptSocket()
'mSocket.Blocking = True
If mSocket.Connected Then
strRemoteIPAddress = Split(mSocket.RemoteEndPoint.ToString, ":")(0)
newConnectionThread = New clsTCPConnection(mSocket, strRemoteIPAddress)
'Start the thread to handle this connection
Form1.addlvDataItem("Connected to " & strRemoteIPAddress.ToString(), 0)
Dim myThread As New System.Threading.Thread(AddressOf newConnectionThread.HandleConnection)
myThread.Start()
End If
End If
End While
Catch ex As Exception
If bServerRunning = True Then
'notify main application
End If
End Try
Loop
End Sub
</code></pre>
<p>and this is what i do in my Form1 class</p>
<pre><code>Public Delegate Sub addlvDataItemCallback(ByVal [text] As String, ByVal Num As Integer)
Public Sub addlvDataItem(ByVal [text] As String, ByVal Type As Integer)
CurrentDateTime = DateTime.Now
If lvData.InvokeRequired Then
Dim d As New addlvDataItemCallback(AddressOf addlvDataItem)
Me.Invoke(d, New Object() {[text]})
Else
If Type = 1 Then 'TX
Me.lvData.Items.Add("TX (" + text.Length.ToString() + " bytes): " + CurrentDateTime + " : <Start> " + text.ToString() + "<End>")
ElseIf Type = 2 Then
Me.lvData.Items.Add("RX (" + text.Length.ToString() + " bytes): " + CurrentDateTime + " : <Start> " + text.ToString() + "<End>")
Else
Me.lvData.Items.Add("Info: " + CurrentDateTime + " : " + text.ToString())
End If
End If
End Sub
</code></pre>
<p>The new text that I add is not displayed in the listview. I do not get any compile or runtime errors but still no new text to list box. I can add text from my Form1 class but not from the thread.</p>
| 3 | 1,168 |
Encoding error that only shows in the Interactive Window
|
<h2>Summary</h2>
<p>I am making a program in python, and I've finished it, ran it in shell and it worked perfectly. However when I run the program in the Interactive Window, it produces an error while in the idle window, it doesn't.</p>
<h2>Crash information</h2>
<p>Picture of the error before the window crashes:</p>
<p><a href="https://i.stack.imgur.com/0mEwZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0mEwZ.png" alt="Error Before crash"></a></p>
<pre><code>### COFFEE SHOP APP ###
# IMPORTS
from Motto import ourMotto
import time
import os
import sys
# MAIN CODE
def CoffeeShopApp():
# VARIABLES
orderCost = 0
smallCost = 2.00
mediumCost = 3.50
largeCost = 4.75
spicyCost = 5.25
coffeeInput = False
sugarCost = 0.05
sugarInput = False
syrupCost = 0.50
syrupInput = False
print("Welcome to the Michael the Moose Coffee App - Where the price is right")
print("You've tried BartSucks, and it sucks so now try the best")
print("We will guide you through the ordering process and our amazing Barista 'Michelle' in Barcelona will then serve you\n")
print("And our amazing Barista 'Michelle' in Barcelona will then serve you\n")
while coffeeInput == False:
tempSize = input(
"""
What size would you like your coffee?
Small - 2€, Medium - 3.50€, Large - 4.75€ or Spicy - 5.25€
"""
)
tempSize = tempSize.title()
if tempSize == "Small":
coffeeSize = "Small"
coffeeInput = True
orderCost = (orderCost + smallCost)
elif tempSize == "Medium":
coffeeSize = "Medium"
coffeeInput = True
orderCost = (orderCost + mediumCost)
elif tempSize == "Large":
coffeeSize = "Large"
coffeeInput = True
orderCost = (orderCost + largeCost)
elif tempSize == "Spicy":
coffeeSize = "Spicy"
coffeeInput = True
orderCost = (orderCost + spicyCost)
else:
print("Please enter a valid size")
coffeeInput = False
time.sleep(0.5)
print()
orderCost = str(orderCost)
print("Ok, currently your order costs "+orderCost+"€")
time.sleep(0.5)
print()
while sugarInput == False:
tempSugar = int(input(
"""
How many sugars would you like added to your coffee?
1 sugar - 0.05€, 2 sugars - 0.10€, 3 sugars - 0.15€, 4 sugars - 0.20€:
"""
))
if isinstance(tempSugar, int):
if tempSugar > 4:
print("Please enter a valid number of sugars")
sugarInput = False
time.sleep(0.5)
else:
orderCost = float(orderCost)
orderCost = (orderCost + (tempSugar * sugarCost))
sugarInput = True
else:
print("Please enter a number")
print()
orderCost=str(orderCost)
print("Ok, currently your order costs "+orderCost+"€")
time.sleep(0.5)
print()
while syrupInput == False:
tempSyrup = input(
"""
Would you like syrup? (0.50€):
""")
tempSyrup = tempSyrup.title()
if tempSyrup == "Yes":
syrupInput = True
elif tempSyrup == "No":
syrupInput = True
else:
print("Please enter either yes/no")
time.sleep(0.5)
orderCost = str(orderCost)
print("Alright, your final order cost comes up to: "+orderCost+"€")
name = input("Please enter your name and our barista Michelle will get straight to work on your coffee: ")
name = name.upper()
tempSugar = str(tempSugar)
orderCost = str(orderCost)
lines = ['Here is your new order: It is size: '+tempSize+'',
'There are '+tempSugar+' sugars to be put in the coffee',
'and they have said '+tempSyrup+' to having syrup.',
'Their name is '+name+,
'It will cost: '+orderCost+'€',
'',
'',
'',
'',
'',
'',
'',
ourMotto]
with open('MichelleMooseCoffeeOrders.txt', 'w') as MMC:
for l in lines:
MMC.write(l + '\n')
MMC.close()
print(
"""
Your order has been proccessed
Please come and collect your order at the shop within the hour,
or your order will be incinerated
"""
)
input("Press ENTER to exit the app")
if mode == 'Interactive' or mode == 'I':
os.system('cls')
mode = input("Are you in shell/interactive mode?")
mode = mode.title()
if mode == 'Interactive' or mode == 'I':
os.system('cls')
input("Slide left to sign in")
if mode == 'Interactive' or mode == 'I':
os.system('cls')
appreal = False
while appreal == False:
app = input(
"""
What app would you like to use?
Coffee Shop, (more coming sometime soon)
"""
)
app = app.title()
if app == 'Coffee Shop' or app == 'Cs':
if mode == 'Interactive' or mode == 'I':
os.system('cls')
CoffeeShopApp()
elif app == '':
pass
</code></pre>
<p>Line 169 is a call for a subroutine</p>
<p>Line 30 is an end of a print shaped like this:</p>
<pre><code>print(
"""
*text here*
"""
)
</code></pre>
<p>And the line 12 seems to refer to a program in the python files.
In the program it imports a variable from a python program in the same location as this question.</p>
<h2>Related Files</h2>
<p>The imported file is this:</p>
<pre><code>ourMotto = ('You have been playing for over an hour. Please do not forget to take a break.')
</code></pre>
<p>It writes to a text file in the same file location named:</p>
<p>MichelleMooseCoffeeOrders</p>
<p>If you need me to add any more information about the program or help me format this question, then leave a comment. (I'm new to stack overflow and am still learning how to format questions so feedback helps)</p>
<p>error code after utf-8 encoding:</p>
<pre><code> Traceback (most recent call last):
File"Z:\Year9\LessonWork\I.C.T\ComputerScience(Wednesday)\Programming\CoffeeShopApp\CoffeeShopApp.p, line 169, in <module>
CoffeeShopApp
File"Z:\Year9\LessonWork\I.C.T\ComputerScience(Wednesday)\Programming\CoffeeShopApp\CoffeeShopApp.py", line 30, in CoffeeShopApp
"""
File "C:\Program Files (x86)\Python35-32\lib\encoding\cp850.py", line 12, in encode
return codecs.charmaps_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 76:P character maps to <undefined>
</code></pre>
| 3 | 2,958 |
Elasticsearch Curator
|
<p>I am using ElasticSearch Version 1.7.2. I want to take a snapshot with help of the curator. I followed a link get to know that it gives me an incremental snapshot but I didn't get any incremental snapshot of my index.</p>
<p>I have 1 index <code>test</code> having 50,000 docs. I have taken a snapshot of that index. After inserting 100,000 docs in the same index, I again took a snapshot of that index. But when I check it, it's showing me the same data in both my snapshots.</p>
<p>What's the difference between those? I don't think it is incremental in any way. Please help me out.</p>
<p>PS: I only want to backup the remaining 100,000, not the whole data.</p>
<p>Output of <code>GET /_snapshot/my_backup/_all</code>:</p>
<pre><code>{
"snapshots": [
{
"snapshot": "curator-20160509052605",
"version_id": 1070199,
"version": "1.7.1",
"indices": [
"jal"
],
"state": "SUCCESS",
"start_time": "2016-05-09T05:26:05.735Z",
"start_time_in_millis": 1462771565735,
"end_time": "2016-05-09T05:26:06.282Z",
"end_time_in_millis": 1462771566282,
"duration_in_millis": 547,
"failures": [],
"shards": {
"total": 5,
"failed": 0,
"successful": 5
}
},
{
"snapshot": "curator-20160509055355",
"version_id": 1070199,
"version": "1.7.1",
"indices": [
"jal"
],
"state": "SUCCESS",
"start_time": "2016-05-09T05:53:55.824Z",
"start_time_in_millis": 1462773235824,
"end_time": "2016-05-09T05:53:56.737Z",
"end_time_in_millis": 1462773236737,
"duration_in_millis": 913,
"failures": [],
"shards": {
"total": 5,
"failed": 0,
"successful": 5
}
},
{
"snapshot": "curator-20160509060002",
"version_id": 1070199,
"version": "1.7.1",
"indices": [
"jal"
],
"state": "SUCCESS",
"start_time": "2016-05-09T06:00:02.282Z",
"start_time_in_millis": 1462773602282,
"end_time": "2016-05-09T06:00:03.602Z",
"end_time_in_millis": 1462773603602,
"duration_in_millis": 1320,
"failures": [],
"shards": {
"total": 5,
"failed": 0,
"successful": 5
}
}
]
}
</code></pre>
| 3 | 1,058 |
Keep an element scrolled to the bottom
|
<p>I am creating a "log" screen that updates periodically in React. To make sure that the latest addition is always in view I would like the element to always be scrolled to the bottom:</p>
<p><a href="https://i.stack.imgur.com/tMXHL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tMXHL.png" alt="Example of what I want to acheive" /></a></p>
<p>I have the overflow working:</p>
<h1>CSS:</h1>
<pre><code>div.log {
height: 200px;
overflow: auto;
}
</code></pre>
<p>And the HTML:</p>
<h1>JSX:</h1>
<pre><code>render() {
return (
<div className="log">
<ul>
{this.props.log.map((log, i) =>
<li key={i}>
{log.message}
</li>
)}
</ul>
</div>
);
}
</code></pre>
<p>Here is my entire component:</p>
<h1>Javascript</h1>
<pre><code>import React from 'react';
export default class Log extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="log">
<ul>
{this.props.log.map((log, i) =>
<li key={i}>
{log.message}
</li>
)}
</ul>
</div>
);
}
}
</code></pre>
<p>This all works fine, but doesn't stay scrolled down. I understand that I can use something similar to:</p>
<pre><code> var element = document.getElementByClassName(".log");
element.scrollTop = element.scrollHeight;
</code></pre>
<p>But this only works once, I need to be scrolled to the bottom when the contents of ".log" updates.</p>
<p>Any help is much appreciated.</p>
| 3 | 1,029 |
aio_write() and lio_listio() of POSIX AIO don't work correctly in write operation
|
<p>I'm setting up a asynchronized writer and want operation order on file be guaranteed by that. I use it as writer in another program which read a pcap file. Consider I have already tried to use both linux-aio and POSIX aio in my code seperately, to write pcap file on disk. I need to know are aio_write() and lio_listio() of POSIX AIO guaranteed to be executed in order?</p>
<p>In linux-aio I use iocb structure to represent a single request for write operation. After fixed number of single operation, io_getevents blocks until fixed number completion report.</p>
<pre><code>struct iocb io_cb;
memset(&io_cb, 0, sizeof(io_cb));
io_cb.aio_fildes = file_descriptor;
io_cb.aio_lio_opcode = IOCB_CMD_PWRITE;
io_cb.aio_reqprio = 0;
io_cb.aio_buf = (__u64)(buffer);
io_cb.aio_nbytes = size;
io_cb.aio_offset = 0;
struct iocb* io_cb_pointer = &io_cb;
static int32_t BLOCKS_COUNT = 1;
syscall(SYS_io_submit, io_context, BLOCKS_COUNT, &io_cb_pointer)
write_count++;
if ((write_count == MAX_EVENT_COUNT) || flush == true)//flush is to flush before exit program.
{
struct io_event* events = (struct io_event *)malloc((write_count) * sizeof(struct io_event));
syscall(SYS_io_getevents, io_context, write_count / 2, MAX_EVENT_COUNT, events, NULL)
}
</code></pre>
<p>above piece of code which is writing responsible results in proper pcap output that can be opened by Wireshark.</p>
<p>But my problem is with POSIX aio which seem doesn't guarantee order of operation in execution. The piece of writing code is demonstrated in below:</p>
<pre><code> aiocb_array = calloc(MAX_EVENT_COUNT, sizeof (struct aiocb*));
aiocb_element = calloc(MAX_EVENT_COUNT, sizeof (struct aiocb));
...
struct aiocb** aiocb_array;
struct aiocb* aiocb_element;
...
static size_t pre_nbytes = 0;
static __off_t pre_offset = 24;//Due to pcap header file length
aiocb_element[write_count].aio_fildes = file_descriptor;
aiocb_element[write_count].aio_lio_opcode = LIO_WRITE;
aiocb_element[write_count].aio_reqprio = 0;
aiocb_element[write_count].aio_buf = (void *)(buffer);
aiocb_element[write_count].aio_nbytes = size;
aiocb_element[write_count].aio_offset = pre_nbytes + pre_offset;
pre_nbytes = size;
pre_offset = aiocb_element[write_count].aio_offset;
aiocb_array[write_count] = &aiocb_element[write_count];
write_count++;
if ((write_count == MAX_EVENT_COUNT) || flush == true )//flush is to flush before exit program.
{
if(flush)
{
if(lio_listio(LIO_WAIT, aiocb_array, write_count, NULL) != 0)
{
printf("Flush lio_listio errno :%d\n", errno);
input->error_code = errno;
return false;
}
}
else
{
if(lio_listio(LIO_NOWAIT, aiocb_array, write_count, NULL) != 0)
{
printf("lio_listio errno :%d\n", errno);
input->error_code = errno;
return false;
}
}
if(write_count == MAX_EVENT_COUNT)
write_count = 0;
}
</code></pre>
<p>As clear in above code, I prepare write request in aiocb structure and assign it's offset, because the file that is used to write was opened without append mode. the piece of code generates pcap file that has same byte like input pcap but unfortunately Wireshark can't open it and show error that indicate:"The capture file appears to be damaged or corrupt. (pcap: File has .......-byte packet, bigger than maximum 0f 65535)". But when I call lio_listio with LIO_WAIT mode and set MAX_EVENT_COUNT = 1, it generates proper pcap output that can be opened by Wireshark correctly.</p>
<p>In addition when I replace lio_listio with aio_write function of POSIX, it produces corrupted file again.
According to mentioned condition which results in proper output pcap, it seems that lio_listio and aio_write function of POSIX execution order are different with program submit order!!!
Does it carried out the operations in arbitrary order? if the answer is yes why it ignore offset value and proper output are not generated? why linux-aio guarantee and keep operation order?
if the answer is no so what is my code and logic problem?</p>
<p>Any help will be appreciated.</p>
| 3 | 1,682 |
XPath Exclude nodes based on attributes of multiple other nodes
|
<p>I'm trying to write XPath against the XML below that will get me all nodes in the list with @id='ResponseActionList' for a specific @rsp_cd where the @act_cd does not exist in the list with @id='ActExcludeList'</p>
<pre><code><resp-env>
<cmd-resp>
<static>
<list id="ResponseActionList">
<listRow rsp_cd="R1" act_cd="A1" act_tx="A1 Text"/>
<listRow rsp_cd="R1" act_cd="A2" act_tx="A2 Text"/>
<listRow rsp_cd="R1" act_cd="A4" act_tx="A4 Text"/>
<listRow rsp_cd="R1" act_cd="A5" act_tx="A5 Text"/>
<listRow rsp_cd="R1" act_cd="A6" act_tx="A6 Text"/>
<listRow rsp_cd="R1" act_cd="A7" act_tx="A7 Text"/>
<listRow rsp_cd="R2" act_cd="A1" act_tx="A1 Text"/>
<listRow rsp_cd="R2" act_cd="A2" act_tx="A2 Text"/>
<listRow rsp_cd="R2" act_cd="A3" act_tx="A3 Text"/>
<listRow rsp_cd="R2" act_cd="A4" act_tx="A4 Text"/>
<listRow rsp_cd="R2" act_cd="A5" act_tx="A5 Text"/>
<listRow rsp_cd="R2" act_cd="A6" act_tx="A6 Text"/>
</list>
<list id="ActExcludeList">
<listRow act_cd="A2"/>
<listRow act_cd="A3"/>
</list>
</static>
</cmd-resp>
</resp-env>
</code></pre>
<p>I can easily get all the nodes containing the appropriate @rsp_cd with this:</p>
<pre><code>//static/list[@id='ResponseActionList']/listRow[@rsp_cd='R2']
</code></pre>
<p>And I can exclude nodes for a particular @act_cd with this:</p>
<pre><code>//static/list[@id='ResponseActionList']/listRow[@rsp_cd='R2' and @act_cd!='A2']
</code></pre>
<p>What I want is to exclude all nodes from the first expression above where the @act_cd attribute is not in the results of this expression:</p>
<pre><code>//static/list[@id='ActExcludeList']/listRow/@act_cd
</code></pre>
<p>I tried something like this, which I didn't expect to work, and I'm not sure what to try next:</p>
<pre><code>//static/list[@id='ResponseActionList']/listRow[@rsp_cd='R2' and not(contains(//static/list[@id='ActExcludeList']/listRow/@act_cd,@act_cd))]
</code></pre>
| 3 | 1,133 |
crud delete all rows
|
<p>I'm trying to delete all rows from my database using crud and this is my delete response page.
I tried the query delete * but that didn't work so I've manually typed it up like this. The values are coming up as unidentified indexes. Can anyone help, tell me what I'm doing wrong or give an easier method please?</p>
<pre><code><?php
include "library.php";
include "database.php";
?>
<?php
//Get data from form
$faculty=$_POST["faculty"];
$date=$_POST["date"];
$modulecode=$_POST["modulecode"];
$moduletitle=$_POST["moduletitle"];
$school=$_POST["school"];
$modulebookcontent=$_POST["modulebookcontent"];
$moduleorganisation=$_POST["moduleorganisation"];
$lrcmaterials=$_POST["lrcmaterials"];
$moduledifficulty=$_POST["moduledifficulty"];
$modulesimilarity=$_POST["modulesimilarity"];
$contentinteresting=$_POST["contentinteresting"];
$previousknowledge=$_POST["previousknowledge"];
$understoodassessmentrequirements=$_POST["understoodassessmentrequirements"];
$assessmentmethod=$_POST["assessmentmethod"];
$markedwork=$_POST["markedwork"];
$ML_interestforsubject=$_POST["ML_interestforsubject"];
$ML_contentclear=$_POST["ML_contentclear"];
$ML_appropriateteachingpace=$_POST["ML_appropriateteachingpace"];
$ML_reachableforadvice=$_POST["ML_reachableforadvice"];
$ML_helpfulfeedback=$_POST["ML_helpfulfeedback"];
$L1_interestforsubject=$_POST["L1_interestforsubject"];
$L1_contentclear=$_POST["L1_contentclear"];
$L1_appropriateteachingpace=$_POST["L1_appropriateteachingpace"];
$L1_reachableforadvice=$_POST["L1_reachableforadvice"];
$L1_helpfulfeedback=$_POST["L1_helpfulfeedback"];
$L2_interestforsubject=$_POST["L2_interestforsubject"];
$L2_contentclear=$_POST["L2_contentclear"];
$L2_appropriateteachingpace=$_POST["L2_appropriateteachingpace"];
$L2_reachableforadvice=$_POST["L2_reachableforadvice"];
$L2_helpfulfeedback=$_POST["L2_helpfulfeedback"];
$moduleleader=$_POST["moduleleader"];
$lecturer1=$_POST["lecturer1"];
$lecturer2=$_POST["lecturer2"];
$indpstudy=$_POST["indpstudy"];
$attendance=$_POST["attendance"];
$bestfeatures=$_POST["bestfeatures"];
$improvemodule=$_POST["improvemodule"];
$queryString = "delete from studentanswers where faculty=".$faculty;
$queryString = "delete from studentanswers where date=".$date;
$queryString = "delete from studentanswers where modulecode=".$modulecode;
$queryString = "delete from studentanswers where moduletitle=".$moduletitle;
$queryString = "delete from studentanswers where school=".$school;
$queryString = "delete from studentanswers where modulebookcontent=".$modulebookcontent;
$queryString = "delete from studentanswers where moduleorganisation=".$moduleorganisation;
$queryString = "delete from studentanswers where lrcmaterials=".$lrcmaterials;
$queryString = "delete from studentanswers where moduledifficulty=".$moduledifficulty;
$queryString = "delete from studentanswers where modulesimilarity=".$modulesimilarity;
$queryString = "delete from studentanswers where contentinteresting=".$contentinteresting;
$queryString = "delete from studentanswers where previousknowledge=".$previousknowledge;
$queryString = "delete from studentanswers where understoodassessmentrequirements=".$understoodassessmentrequirements;
$queryString = "delete from studentanswers where assessmentmethod=".$assessmentmethod;
$queryString = "delete from studentanswers where markedwork=".$markedwork;
$queryString = "delete from studentanswers where ML_interestforsubject=".$ML_interestforsubject;
$queryString = "delete from studentanswers where ML_contentclear=".$ML_contentclear;
$queryString = "delete from studentanswers where ML_appropriateteachingpace=".$ML_appropriateteachingpace;
$queryString = "delete from studentanswers where ML_reachableforadvice=".$ML_reachableforadvice;
$queryString = "delete from studentanswers where ML_helpfulfeedback=".$ML_helpfulfeedback;
$queryString = "delete from studentanswers where L1_interestforsubject=".$L1_interestforsubject;
$queryString = "delete from studentanswers where L1_contentclear=".$L1_contentclear;
$queryString = "delete from studentanswers where L1_appropriateteachingpace=".$L1_appropriateteachingpace;
$queryString = "delete from studentanswers where L1_reachableforadvice=".$L1_reachableforadvice;
$queryString = "delete from studentanswers where L1_helpfulfeedback=".$L1_helpfulfeedback;
$queryString = "delete from studentanswers where L2_interestforsubject=".$L2_interestforsubject;
$queryString = "delete from studentanswers where L2_contentclear=".$L2_contentclear;
$queryString = "delete from studentanswers where L2_appropriateteachingpace=".$L2_appropriateteachingpace;
$queryString = "delete from studentanswers where L2_reachableforadvice=".$L2_reachableforadvice;
$queryString = "delete from studentanswers where L2_helpfulfeedback=".$L2_helpfulfeedback;
$queryString = "delete from studentanswers where moduleleader=".$moduleleader;
$queryString = "delete from studentanswers where lecturer1=".$lecturer1;
$queryString = "delete from studentanswers where lecturer2=".$lecturer2;
$queryString = "delete from studentanswers where indpstudy=".$indpstudy;
$queryString = "delete from studentanswers where attendance=".$attendance;
$queryString = "delete from studentanswers where bestfeatures=".$bestfeatures;
$queryString = "delete from studentanswers where improvemodule=".$improvemodule;
queryDatabase($queryString);
?>
<?php CRUDheader("Delete Student Answers"); ?>
<body>
<div id="main">
<div id="content">
<p>Student answers deleted</p>
</div>
</div><?php CRUDmain(); ?>
</body>
</html>
</code></pre>
| 3 | 1,872 |
Python : http.server.HTTPServer : How to close ALL opened files?
|
<p>So basically, I am making an HTTP webhooks server in Python 3 and wanted to add a restart function because shell access is very limited on the server it will be running on.</p>
<p>I found this snippet somewhere on Stack Overflow earlier:</p>
<pre><code>def restart_program():
"""Restarts the current program, with file objects and descriptors
cleanup
"""
try:
p = psutil.Process(os.getpid())
fds = p.open_files() + p.connections()
print (fds)
for handler in fds:
os.close(handler.fd)
except Exception as e:
logging.error(e)
python = sys.executable
os.execl(python, python, *sys.argv)
</code></pre>
<p>For the most part, it works, but I wanted to make sure so I ran a few tests with <code>lsof</code> and found that every time I restarted the server, two more lines (files) were added to the list of open files:</p>
<pre><code>python3 13923 darwin 5u systm 0x18cd0c0bebdcbfd7 0t0 [ctl com.apple.netsrc id 9 unit 36]
python3 13923 darwin 6u unix 0x18cd0c0beb8fc95f 0t0 ->0x18cd0c0beb8fbcdf
</code></pre>
<p>(the adresses varying each restart)</p>
<p>These are only present when I initiate <code>httpd = ThreadingSimpleServer((host, port), Handler)</code>. But even after I call <code>httpd.server_close()</code> these open files persist and psutil doesn't seem to find them.</p>
<p>This isn't really required feature. If this proves to be too much overhead I can drop it, but right now I am only interested in why my code doesn't work and a solution for my own sanity.</p>
<p>Thanks in advance!</p>
<p><strong>UPDATE</strong>:</p>
<p>Changing <code>p.connections()</code> to <code>p.connections(kind='all')</code> got me the <code>unix</code> type fd. Still not sure how to close the <code>systm</code> type fd. Turns out the <code>unix</code> fd had to do with DNS...</p>
<p><strong>UPDATE</strong>:</p>
<p>Well, it looks like I found a solution, however messy it may be.</p>
<pre><code>class MyFileHandler(object):
"""docstring for MyFileHandler."""
def __init__(self, fd):
super(MyFileHandler, self).__init__()
self.fd = fd
def get_open_systm_files(pid=os.getpid()):
proc = subprocess.Popen(['lsof', '-p', str(pid)], stdout=subprocess.PIPE)
return [MyFileHandler(int(str(l).split(' ')[6][:-1])) for l in proc.stdout.readlines() if b'systm' in l]
def restart_program():
"""Restarts the current program, with file objects and descriptors
cleanup
"""
try:
p = psutil.Process(os.getpid())
fds = p.open_files() + p.connections()
print (fds)
for handler in fds:
os.close(handler.fd)
except Exception as e:
logging.error(e)
python = sys.executable
os.execl(python, python, *sys.argv)
</code></pre>
<p>It's not pretty, but it works.</p>
<p>If anyone could shed some light on what actually is/was going on I would very much like to know.</p>
| 3 | 1,177 |
Getting a value back from a child component after it is routed in ReactJS
|
<p>I am new to react and currently I am stuck in a scenario where I have 2 components,</p>
<ol>
<li>Launcher Component</li>
<li>Developer component</li>
</ol>
<p>In this, Launcher Component is called first.From that on button click it routes to Developer component. I want to pass a value back from Developer component to Launcher component after routing.</p>
<p>Launcher.js</p>
<pre><code>class LauncherApp extends Component {
constructor(props) {
super(props);
this.developerMode = this.developerMode.bind(this)
}
developerMode(){
this.props.history.push('/dev') //routes to developer component
}
render() {
return (
<div>
<List>
<ListItem
onClick={this.developerMode}>Developer<ListItem/>
</List>
</div>
);
}
}
</code></pre>
<p>Developer.js</p>
<pre><code>class DeveloperMode extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
url:'Prod'
};
}
handleChange(event) {
this.setState({
url: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
var env=this.state.url;
this.props.signOut();
}
render() {
return(
<div>
<h3>Select Environment </h3>
<RadioButtonGroup name="selectURL" defaultSelected="Prod" onChange={this.handleChange}>
<RadioButton
value="Prod"
label="Production"
/>
<RadioButton
value="Dev"
label="Development"
/>
<RadioButton
value="Test"
label="Testing"
/>
</RadioButtonGroup>
<RaisedButton label="Save" onClick={this.handleSubmit}/>
</div>
);
}
}
</code></pre>
<p>Routes.js</p>
<pre><code>const Routes = () => (
<Router>
<div>
<Route component={LauncherApp}/>
<Switch>
<Route exact path={"/"} component={ApplicationList} />
<Route path={"/dev"} component={DeveloperMode} />
</Switch>
</div>
</Router>
);
</code></pre>
<p>Is there any way that I can get the value 'url' from developer component when it is routed in Launcher.js</p>
| 3 | 1,400 |
Unusual Behavior observed while calling main() in any other function in c++
|
<p>I made a simple program to test whether I am able to call main in any other function like we call different functions in other function.</p>
<p>Therefore, I made a program to generate the maximum number by getting input of 3 numbers from the user. For this I made the function containing if else. Surprisingly (especially for me) it worked. I got that I am keep inputting the numbers then I made another variable to control the inputs. I made it to input 3 times. I got answer from bottom to end and 3 answers are generated.</p>
<pre><code>#include <iostream>
using namespace std;
int main();
void max(int a, int b, int c,int p);
int p = 0;
int main()
{
p++;
int a, b, c;
cout << "\n\n";
cout << "Enter 1st number :\t";
cin >> a;
cout << "Enter 2nd number :\t";
cin >> b;
cout << "Enter 3rd number :\t";
cin >> c;
max(a, b, c, p);
cout << "\n\n\n";
system("pause");
return 0;
}
void max(int a, int b, int c,int p)
{
if (p < 3)
{
main();
}
if (a > b&&a > c)
{
cout << a << " is maximum";
}
else if (b > a&&b > c)
{
cout << b << " is maximum";
}
else
{
cout << c << " is maximum";
}
}
</code></pre>
<p>The output was as follows: -</p>
<pre><code>
Enter 1st number : 12
Enter 2nd number : 14
Enter 3rd number : 15
Enter 1st number : 45
Enter 2nd number : 69
Enter 3rd number : 88
Enter 1st number : 14
Enter 2nd number : 20
Enter 3rd number : 11
20 is maximum
Press any key to continue . . .
88 is maximum
Press any key to continue . . .
15 is maximum
Press any key to continue . . .
</code></pre>
<p>I don't get the logic behind it. I used Visual Studio 2017 for this.</p>
| 3 | 2,671 |
Chrome extensions (can't get and click elements on new chrome tabs)
|
<p>That's it. Lemme explaim myself.
I coded a chrome extension that when clicking on a button, it will open a new resized tab (a paypal login) , but I can't manage to click the "log in button" of paypal because trying to</p>
<pre><code>document.getElementById('btnLogin').click();
</code></pre>
<p>isn't working, neither adding that:</p>
<pre><code>var paypal = window.open("https://www.paypal.com/es/signin", "PayPal", "width=400,height=400,location=yes,menubar=yes,status=yes,titilebar=yes,resizable=yes");
paypal.onload = function() {
paypal.document.getElementById('btnLogin').click();
}
</code></pre>
<p>Check out all of my code:</p>
<p><strong>manifest.json</strong></p>
<pre><code>{
"manifest_version": 2,
"name": "Zapatillao",
"description": "Yatusabe te cojo sapatilla",
"version": "2.0.0",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"browser_action": {
"default_popup": "popup.html",
"default_icon": "icon128.jpg"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"chrome://*/*"
]
}
</code></pre>
<p><strong>content.js</strong></p>
<pre><code>document.getElementById('paypal_prelog').addEventListener('click', function() {
chrome.tabs.executeScript({
file: "paypal_prelog.js"
});
});
</code></pre>
<p><strong>popup.html</strong></p>
<pre><code><html>
<head>
<style>
html, body {
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<h1>Discord: Loan#2334</h1>
<button id='paypal_prelog'>PayPal Prelogin</button>
<script src='content.js'></script>
</body>
</html>
</code></pre>
<p><strong>paypal_prelog.js</strong></p>
<pre><code>function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var paypal = window.open("https://www.paypal.com/es/signin", "PayPal", "width=400,height=400,location=yes,menubar=yes,status=yes,titilebar=yes,resizable=yes");
paypal.onload = function() {
paypal.document.getElementById('btnLogin').click();
}
function closeWin() {
paypal.close();
}
</code></pre>
<blockquote>
<p>I have tried thousand of things, hope you can help me.</p>
</blockquote>
| 3 | 1,299 |
Testing Asynchronous Code (useEffect + fetch) In React Components
|
<p>I'm trying to figure out how to test components that update state using useEffect to make an API call to get data. There are several things I think are important to know before I can talk anymore, and that is the files/packages I'm using.</p>
<p>First, I have a main component called <code>App.tsx</code>, inside <code>App.tsx</code>, inside of useEffect, I make a fetch call to an external API to fetch an array of songs by Queen. I also render out a <code><Song /></code> component using <code>.map</code> to iterate over each song and <code>.filter</code> to filter songs on UI based on text input. I'm using a custom hook. Here is the code I have for that component and its custom hook.</p>
<pre><code>// App.tsx
type ISong = {
id: number;
title: string;
lyrics: string;
album: string;
};
export default function App() {
const { songs, songError } = useSongs();
const { formData, handleFilterSongs } = useForm();
return (
<Paper>
<h1>Queen Songs</h1>
<FilterSongs handleFilterSongs={handleFilterSongs} />
<section>
{songError ? (
<p>Error loading songs...</p>
) : !songs ? (
<>
<p data-testid="loadingText">Loading...</p>
<Loader />
</>
) : (
<Grid container>
{songs
.filter(
(song: ISong) =>
song.title
.toLowerCase()
.includes(formData.filter.toLowerCase()) ||
song.album
.toLowerCase()
.includes(formData.filter.toLowerCase()) ||
song.lyrics
.toLowerCase()
.split(" ")
.join(" ")
.includes(formData.filter.toLowerCase())
)
.map((song: ISong) => (
<Grid key={song.id} item>
<Song song={song} />
</Grid>
))}
</Grid>
)}
</section>
</Paper>
);
}
</code></pre>
<pre><code>// useSongs.tsx
type ISongs = {
id: number;
title: string;
lyrics: string;
album: string;
}[];
type IError = {
message: string;
};
export default function useSongs() {
const [songs, setSongs] = useState<ISongs | null>(null);
const [songError, setSongError] = useState<IError | null>(null);
useEffect(() => {
fetch("https://queen-songs.herokuapp.com/songs")
.then(res => res.json())
.then(songs => setSongs(songs))
.catch(err => setSongError(err));
}, []);
return {songs, songError}
}
</code></pre>
<p>Next up is my App.test.tsx file. I am using <code>react-testing-library</code> and <code>jest-dom/extend-expect</code> for my testing coverage. Here is my testing file code. I've been watching a youtube tutorial on the matter and I've read a bunch of articles, but I still can't figure this out.</p>
<pre><code>// App.test.tsx
import * as rctl from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import App from "./App";
// @ts-ignore
global.fetch = jest.fn(() =>
Promise.resolve({
json: () =>
Promise.resolve({
value: [{title: "title1", album: "album1", lyrics: "asdf", id: 1}, {title: "title2", album: "album2", lyrics: "zxcv", id: 2}, etc...],
}),
})
);
describe.only("The App component should", () => {
it("load songs from an API call after initial render", async () => {
await rctl.act(async () => {
await rctl.render(<App />).debug();
rctl.screen.debug();
});
});
});
</code></pre>
<p>This code gives me the following error message</p>
<pre><code>
FAIL src/pages/App/App.test.tsx
App
× loads the songs on render (117 ms)
● App › loads the songs on render
TypeError: Cannot read property 'then' of undefined
17 |
18 | useEffect(() => {
> 19 | fetch("https://queen-songs.herokuapp.com/songs")
| ^
20 | .then(res => res.json())
21 | .then(songs => {
22 | setSongs(songs)
at src/pages/App/useSongs.ts:19:7
at invokePassiveEffectCreate (node_modules/react-dom/cjs/react-dom.development.js:23487:20)
at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:3994:16)
at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:4056:31)
at flushPassiveEffectsImpl (node_modules/react-dom/cjs/react-dom.development.js:23574:9)
at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12)
at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
at flushPassiveEffects (node_modules/react-dom/cjs/react-dom.development.js:23447:14)
at Object.<anonymous>.flushWork (node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
at flushWorkAndMicroTasks (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1001:5)
at node_modules/react-dom/cjs/react-dom-test-utils.development.js:1080:11
console.log
<body>
<div>
<div
class="MuiPaper-root MuiPaper-elevation1 MuiPaper-rounded"
style="text-align: center; overflow: hidden; min-height: 100vh;"
>
<h1>
Queen Songs
</h1>
<div
style="display: flex; flex-flow: column; justify-content: center; text-align: center;"
>
<input
data-testid="input"
id="filter"
name="filter"
placeholder="Search by title, album name, or lyrics here..."
style="width: 18.75rem; height: 1.875rem; align-self: center; text-align: center; font-style: italic;"
type="text"
/>
</div>
<section
style="display: flex; flex-flow: row wrap; justify-content: center; align-items: center;"
>
<p
data-testid="loadingText"
>
Loading...
</p>
<div
class="line-container"
>
<div
class="line"
data-testid="loader-line"
/>
</div>
</section>
</div>
</div>
</body>
at Object.debug (node_modules/@testing-library/react/dist/pure.js:107:13)
console.log
<body>
<div>
<div
class="MuiPaper-root MuiPaper-elevation1 MuiPaper-rounded"
style="text-align: center; overflow: hidden; min-height: 100vh;"
>
<h1>
Queen Songs
</h1>
<div
style="display: flex; flex-flow: column; justify-content: center; text-align: center;"
>
<input
data-testid="input"
id="filter"
name="filter"
placeholder="Search by title, album name, or lyrics here..."
style="width: 18.75rem; height: 1.875rem; align-self: center; text-align: center; font-style: italic;"
type="text"
/>
</div>
<section
style="display: flex; flex-flow: row wrap; justify-content: center; align-items: center;"
>
<p
data-testid="loadingText"
>
Loading...
</p>
<div
class="line-container"
>
<div
class="line"
data-testid="loader-line"
/>
</div>
</section>
</div>
</div>
</body>
at logDOM (node_modules/@testing-library/dom/dist/pretty-dom.js:82:13)
console.error
Error: Uncaught [TypeError: Cannot read property 'then' of undefined]
at reportException (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:62:24)
at innerInvokeEventListeners (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:341:9)
at invokeEventListeners (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
at HTMLUnknownElementImpl._dispatch (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:221:9)
at HTMLUnknownElementImpl.dispatchEvent (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:94:17)
at HTMLUnknownElement.dispatchEvent (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:231:34)
at Object.invokeGuardedCallbackDev (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:3994:16)
at invokeGuardedCallback (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:4056:31)
at flushPassiveEffectsImpl (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:23574:9)
at unstable_runWithPriority (C:\Users\brian\Code\cra-queen-api-fe\node_modules\scheduler\cjs\scheduler.development.js:468:12) TypeError: Cannot read property 'then' of undefined
at C:\Users\brian\Code\cra-queen-api-fe\src\pages\App\useSongs.ts:19:7
at invokePassiveEffectCreate (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:23487:20)
at HTMLUnknownElement.callCallback (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:3945:14)
at HTMLUnknownElement.callTheUserObjectsOperation (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\generated\EventListener.js:26:30)
at innerInvokeEventListeners (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:338:25)
at invokeEventListeners (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
at HTMLUnknownElementImpl._dispatch (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:221:9)
at HTMLUnknownElementImpl.dispatchEvent (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:94:17)
at HTMLUnknownElement.dispatchEvent (C:\Users\brian\Code\cra-queen-api-fe\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:231:34)
at Object.invokeGuardedCallbackDev (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:3994:16)
at invokeGuardedCallback (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:4056:31)
at flushPassiveEffectsImpl (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:23574:9)
at unstable_runWithPriority (C:\Users\brian\Code\cra-queen-api-fe\node_modules\scheduler\cjs\scheduler.development.js:468:12)
at runWithPriority$1 (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:11276:10)
at flushPassiveEffects (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom.development.js:23447:14)
at Object.<anonymous>.flushWork (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom-test-utils.development.js:992:10)
at flushWorkAndMicroTasks (C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom-test-utils.development.js:1001:5)
at C:\Users\brian\Code\cra-queen-api-fe\node_modules\react-dom\cjs\react-dom-test-utils.development.js:1080:11
at processTicksAndRejections (node:internal/process/task_queues:94:5)
at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
at reportException (node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:28)
at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:341:9)
at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
console.error
The above error occurred in the <App> component:
at App (C:\Users\brian\Code\cra-queen-api-fe\src\pages\App\App.tsx:18:32)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
at logCapturedError (node_modules/react-dom/cjs/react-dom.development.js:20085:23)
at update.callback (node_modules/react-dom/cjs/react-dom.development.js:20118:5)
at callCallback (node_modules/react-dom/cjs/react-dom.development.js:12318:12)
at commitUpdateQueue (node_modules/react-dom/cjs/react-dom.development.js:12339:9)
at commitLifeCycles (node_modules/react-dom/cjs/react-dom.development.js:20736:11)
at commitLayoutEffects (node_modules/react-dom/cjs/react-dom.development.js:23426:7)
at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.59 s, estimated 3 s
Ran all test suites related to changed files.
</code></pre>
<p>I honestly am completely lost here, and I have no idea what to do next. My usual problem-solving skills are not helping, so I figured I'd turn to SO for some help. Thank you for reading through all of this and for any help you may be able to provide.</p>
<p>Edit: I stripped the code of most of the CSS in the snippets to make it slightly more readable, so that is why the screen.debug() log includes some CSS and the code doesn't.</p>
<p>Edit: I changed the <code>useEffect</code> method to use async/await and now my tests work, but I still have the same output as before. Here is the updated <code>useEffect</code> and the code output.</p>
<pre><code>// Updated useSongs.tsx
export default function useSongs() {
const [songs, setSongs] = useState<ISongs | null>(null);
const [songError, setSongError] = useState<IError | null>(null);
useEffect(() => {
(async() => {
try {
const fetchSongs = await fetch("https://queen-songs.herokuapp.com/songs");
const data = await fetchSongs.json();
setSongs(data);
} catch (error) {
setSongError(error);
}
})()
}, []);
return {songs, songError}
}
</code></pre>
<pre><code> // Updated testOutput
PASS src/pages/App/App.test.tsx
App
√ loads the songs on render (52 ms)
console.log
<body>
<div>
<div
class="MuiPaper-root MuiPaper-elevation1 MuiPaper-rounded"
style="text-align: center; overflow: hidden; min-height: 100vh;"
>
<h1>
Queen Songs
</h1>
<section
style="display: flex; flex-flow: row wrap; justify-content: center; align-items: center;"
>
<p
data-testid="loadingText"
>
Loading...
</p>
<div
class="line-container"
>
<div
class="line"
data-testid="loader-line"
/>
</div>
</section>
</div>
</div>
</body>
at logDOM (node_modules/@testing-library/dom/dist/pretty-dom.js:82:13)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.878 s, estimated 1 s
Ran all test suites related to changed files.
</code></pre>
<p>I want the test to show the HTML <em>after</em> the useEffect has run and the state has updated, the loading text should be gone.</p>
| 3 | 8,353 |
Tracking Control Structures in Java for Static Code Analysis (Available Expressions)
|
<p>I am writing a program in Java that does Available expression Analysis on a given Java Program. I have managed to extract Generate and Kill set. To keep it simple, I am going with a constraint that will only analyze programs that declare ONE VARIABLE IN ONE LINE (The regex expression works for it with declaration and initialization but, the logic for redefinition of variables is still in progress. This is the reason why it won't correctly detect the kill set).</p>
<p>The problem I am facing right now is that how would I track the loops? conditional statements? all the control structures? like While, for, and if-else statements.</p>
<p>Can anyone please help? what to use for this? how to keep track of the paths? Below are the code files.</p>
<p>Any assistance you can provide would be greatly appreciated. Thank you!</p>
<p><strong>ReadFile.java</strong></p>
<pre><code> // Import the File class
import java.io.File;
// Import this class to handle errors
import java.io.FileNotFoundException;
import java.util.ArrayList;
// Import the Scanner class to read text files
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadFile
{
public static void main(String[] args) {
try {
// Creating an object of the file for reading the stmt
File myObj = new File("./Files/Test.txt");
ArrayList<State> stmts = new ArrayList<State>();
String gen="{ }";
String kill="{ }";
Scanner myReader = new Scanner(myObj);
int i=0;
while (myReader.hasNextLine())
{
String stmt = myReader.nextLine();
boolean def=true;
if(stmt.contains("class") || stmt.contains("{") || stmt.contains("}") || stmt.contains("args[]") || stmt.startsWith("//"))
{
continue;
}
Pattern p = Pattern.compile("^(int|long|float|double)\\s(([\\_\\w\\d])+)");
Matcher m = p.matcher(stmt.trim());
while(m.find())
{
kill = m.group(3);
}
if(stmt.contains("="))
{
String[] exp = stmt.split("=");
for(int l=0; l<exp.length;l++)
{
if(exp[l].contains("+") || exp[l].contains("-") || exp[l].contains("*") || exp[l].contains("/"))
{
gen = exp[l];
}
}
stmts.add(new State(new ArrayList<String>(), i, false, kill,gen,stmt));
gen = "{ }";
kill = "{ }";
i++;
}
myReader.close();
for (int j = 0; j < stmts.size(); j++)
{
System.out.println("Line Number " + stmts.get(j).lineNo);
System.out.println("Statement " + stmts.get(j).statement);
System.out.println("Generated " + stmts.get(j).genSet);
System.out.println("Kill " + stmts.get(j).killSet);
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
</code></pre>
<p><strong>State.java</strong></p>
<pre><code>import java.util.ArrayList;
public class State
{
//Elements
public ArrayList<String> variables = new ArrayList<String>();
public int lineNo;
public boolean isDef;
public String killSet;
public String genSet;
public String statement;
//Constructor
public State(ArrayList<String> al, int ln, boolean def, String kill, String gen, String stmt)
{
for(int i=0;i<al.size();i++)
{
variables.add(al.get(i));
}
lineNo = ln;
isDef = def;
killSet = kill;
genSet = gen;
statement = stmt;
}
}
</code></pre>
| 3 | 2,055 |
Terraform variable error : The given value is not valid
|
<p>I am trying to create a monitoring alert policy using terraform. But in the plan stage i am getting the below error on the variable. Has anyone faced a similar issue in the past ? I am new to terraform and i can trying to create a iterable resource for monitoring alert policy in gcp.</p>
<pre><code> Error: Invalid value for input variable
│
│ on terraform.tfvars line 149:
│ 149: alert_policies = {
│ 150: "composer_alert" = {
│ 151: combiner = "OR"
│ 152: display_name = "Alert Strategy"
│ 153: enabled = "true"
│ 154: conditions = [
│ 155: {display_name = "Bytes used condition"
│ 156: conditions_threshold = {
│ 157: "1" = {
│ 158: comparison = "COMPARISON_GT"
│ 159: duration = "0s"
│ 160: filter = "resource.type = \"cloud_composer_environment\" AND resource.labels.project_id = \"prj-comp-01\" AND metric.type = \"composer.googleapis.com/environment/database/disk/bytes_used\""
│ 161: threshold_value = 1600000000
│ 162: alignment_period = "300s"
│ 163: cross_series_reducer = "REDUCE_NONE"
│ 164: group_by_fields = ["project_id"]
│ 165: per_series_aligner = "ALIGN_MEAN"
│ 166: trigger_count = 1
│ 167: trigger_percent = 100
│ 168: }
│ 169: }
│ 170: }
│ 171: ]
│ 172: notification_channels = [
│ 173: "projects/prj-test-01/notificationChannels/2276385315451985010"
│ 174: ]
│ 175: }
│ 176: }
│
│ The given value is not valid for variable "alert_policies": a number is
│ required.
╵
╷
│ Error: Incorrect variable type
│
│ on variables.tf line 392:
│ 392: variable "alert_policies" {
│
│ The resolved value of variable "alert_policies" is not appropriate: a
│ number is required.
</code></pre>
<p><strong><strong><strong>Variables.tf</strong></strong></strong>****</p>
<pre><code>variable "alert_policies" {
type = map(object({
combiner = optional(string)
display_name = optional(string)
enabled = optional(bool)
uptime_checks = optional(map(object({
duration = number
uptime_check_name = string
ssl_expiry_checks = optional(list(object({
days_left = number
})))
})))
conditions = list(object({
display_name = string
conditions_threshold = map(object({
comparison = string
duration = number
filter = string
threshold_value = number
alignment_period = number
cross_series_reducer = string
group_by_fields = list(string)
per_series_aligner = string
trigger_count = number
trigger_percent = number
}))
notification_channels = optional(list(string))
}))
}))
}
</code></pre>
<p>╵</p>
| 3 | 1,456 |
Shared Preferences doesn't work with Bottom Navigation Bar
|
<p>I have faced an issue on getting data from Shared Preferences. It works anywhere except for win_loss.dart.</p>
<p>Below is the page pulled up right after user signs in. win_loss is pulled up as a part of home_page.dart (default page of bottom navigation bar). Shared preferences data can't be pulled and assigned to userInfo[] when home_page.dart is viewed. I tried Futurebuilder, which doesn't work.</p>
<p>Please help me :)</p>
<p>Thanks,</p>
<p>============ home_page.dart ==================</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:Config/design_Config.dart';
import 'package:CustomWidgetMethod/custom_ListTile.dart';
import 'package:club_Info.dart';
import 'package:ranking.dart';
import 'package:win_Loss.dart';
class HomePage extends StatefulWidget {
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// Sign with Google
final GoogleSignIn _googleSignIn = GoogleSignIn();
// User Info Variables
String _userUid = '';
String _userName = '';
String _userEmail = '';
String _userMemberLevel = '';
List<String> _userClub = [];
String _userTennisLevel = '';
int _userTotalMatchPerDay = 0;
int _userBirthYear = 0;
int _userBirthMonth = 0;
int _userBirthDay = 0;
@override
void initState() {
super.initState();
_userInfo(FirebaseAuth.instance.currentUser!.uid)
.then((_) => _getUserInfoToSharedPreferences());
}
// Shared Preference
final Future<SharedPreferences> _sharedPrefs =
SharedPreferences.getInstance();
//Bottom Navigation Bar
int selectedIndex = 1;
List<Widget> navigationBarItems = [ClubInfo(), WinLoss(), Ranking()].toList();
void onTap(int index) {
setState(() {
selectedIndex = index;
});
}
// SignOut
Future<void> _signOut() async {
await FirebaseAuth.instance.signOut();
await _googleSignIn.signOut();
await _googleSignIn.disconnect();
final SharedPreferences sharedPrefs = await _sharedPrefs;
await sharedPrefs.remove('userUid');
await sharedPrefs.remove('userName');
await sharedPrefs.remove('userEmail');
await sharedPrefs.remove('userMemberLevel');
await sharedPrefs.remove('userClub');
await sharedPrefs.remove('userTennisLevel');
await sharedPrefs.remove('userTotalMatchPerDay');
await sharedPrefs.remove('userBirthYear');
await sharedPrefs.remove('userBirthMonth');
await sharedPrefs.remove('userBirthday');
}
// Get and Save User Info to Shared Preference
Future<void> _userInfo(String userUid) async {
print('aha');
DocumentSnapshot snapshot =
await FirebaseFirestore.instance.collection('users').doc(userUid).get();
if (snapshot.exists) {
Map<String, dynamic>? userInfo = snapshot.data() as Map<String, dynamic>?;
//Generating SharedPreference Instance.
final SharedPreferences sharedPrefs = await _sharedPrefs;
await sharedPrefs.setString('userUid', userInfo?['userUid']);
await sharedPrefs.setString('userName', userInfo?['userName']);
await sharedPrefs.setString('userEmail', userInfo?['userEmail']);
await sharedPrefs.setString(
'userMemberLevel', userInfo?['userMemberLevel']);
List<String> _userClubList = [];
userInfo?['userClub'].forEach((clubInfo) {
print(clubInfo);
_userClubList.add(clubInfo);
print('_UserclubList: $_userClubList');
});
await sharedPrefs.setStringList('userClub', _userClubList);
await sharedPrefs.setString(
'userTennisLevel', userInfo?['userTennisLevel']);
await sharedPrefs.setInt(
'userTotalMatchPerDay', userInfo?['userTotalMatchPerDay']);
await sharedPrefs.setInt('userBirthYear', userInfo?['userBirthYear']);
await sharedPrefs.setInt('userBirthMonth', userInfo?['userBirthMonth']);
await sharedPrefs.setInt('userBirthday', userInfo?['userBirthday']);
}
}
// Get User Info From Shared Preferences.
_getUserInfoToSharedPreferences() async {
SharedPreferences _sharedPrefs = await SharedPreferences.getInstance();
setState(() {
_userUid = _sharedPrefs.getString('userUid') ?? '';
_userName = _sharedPrefs.getString('userName') ?? '';
_userEmail = _sharedPrefs.getString('userEmail') ?? '';
_userMemberLevel = _sharedPrefs.getString('userMemberLevel') ?? '';
_userClub = _sharedPrefs.getStringList('userClub') ?? [];
_userTennisLevel = _sharedPrefs.getString('userTennisLevel') ?? '1.0';
_userTotalMatchPerDay = _sharedPrefs.getInt('userTotalMatchPerDay') ?? 0;
_userBirthYear = _sharedPrefs.getInt('userBirthYear') ?? 0;
_userBirthMonth = _sharedPrefs.getInt('userBirthMonth') ?? 0;
_userBirthDay = _sharedPrefs.getInt('userBirthMonth') ?? 0;
});
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
appBar: AppBar(
title: Text(
_userEmail,
// _userClub.isNotEmpty ? _userClub.first : '가입 클럽 없음',
style: const TextStyle(fontSize: DesignConfig.appBarFontSize),
),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue,
onTap: onTap,
currentIndex: selectedIndex,
type: BottomNavigationBarType.fixed,
selectedFontSize: 50,
unselectedFontSize: 20,
selectedItemColor: Colors.white,
selectedIconTheme: const IconThemeData(color: Colors.white, size: 25),
unselectedIconTheme:
const IconThemeData(color: Colors.black, size: 22),
selectedLabelStyle: const TextStyle(
color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold),
unselectedLabelStyle: const TextStyle(
color: Colors.black, fontSize: 10, fontWeight: FontWeight.bold),
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.cabin),
label: "Info",
),
BottomNavigationBarItem(
icon: Icon(Icons.battery_unknown),
label: "Win or Lost",
),
BottomNavigationBarItem(
icon: Icon(Icons.list_alt),
label: "Ranking",
),
],
),
body: navigationBarItems[selectedIndex],
),
);
}
}
</code></pre>
<p>============ win_loss.dart ==================</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:Config/design_Config.dart';
import 'package:CustomWidgetMethod/custom_CircularProgressIndicator.dart';
import 'package:CustomWidgetMethod/custom_SnackBar.dart';
class WinLoss extends StatefulWidget {
@override
State<WinLoss> createState() => _WinLossState();
}
class _WinLossState extends State<WinLoss> {
// User Info Variables
String _userUid = '';
String _userName = '';
String _userEmail = '';
String _userMemberLevel = '';
List<String> _userClub = [];
String _userTennisLevel = '';
int _userTotalMatchPerDay = 0;
int _userBirthYear = 0;
int _userBirthMonth = 0;
int _userBirthDay = 0;
// Max Match Per Day
int _maxMatchPerDay = 3;
// Scoring
int _matchScore = 0;
int _gameScore = 0;
final Color _selectedColor = Colors.blue;
final Color _unselectedColor = Colors.grey;
// Get Current Time
DateTime now = DateTime.now();
String formattedDate =
DateFormat('yyyy').format(DateTime.now());
// User Info Variables
List<dynamic> userInfo = [];
@override
void initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences _sharedPref) =>
_getUserInfoToSharedPreferences(_sharedPref));
}
// Get User Info From Shared Preferences.
Future<List<dynamic>> _getUserInfoToSharedPreferences(
SharedPreferences sharedPref) async {
userInfo.add(sharedPref.getString('userUid') ?? '');
userInfo.add(sharedPref.getString('userName') ?? '');
userInfo.add(sharedPref.getString('userEmail') ?? '');
userInfo.add(sharedPref.getString('userMemberLevel') ?? '');
userInfo.add(sharedPref.getStringList('userClub') ?? []);
userInfo.add(sharedPref.getString('userTennisLevel') ?? '1.0');
userInfo.add(sharedPref.getInt('userTotalMatchPerDay') ?? 0);
userInfo.add(sharedPref.getInt('userBirthYear') ?? 0);
userInfo.add(sharedPref.getInt('userBirthMonth') ?? 0);
userInfo.add(sharedPref.getInt('userBirthMonth') ?? 0);
return userInfo;
}
Future<int?> _updateScore() async {
setState(() {
// The first "FormattedDate" was inintiled
formattedDate =
DateFormat('yyyy년 MM월 dd일 kk시 mm분').format(DateTime.now());
print('New FormattedDAte: $formattedDate');
});
print(userInfo[0]);
print(userInfo[1]);
print(userInfo[2]);
print(userInfo[3]);
print(userInfo[4][0]);
DocumentReference docRef = FirebaseFirestore.instance
.collection('clubs')
.doc(userInfo[4][0])
.collection('matches')
.doc('match')
.collection('individuals')
.doc(userInfo[2]);
return await docRef.get().then((DocumentSnapshot documentSnapshot) async {
if (!documentSnapshot.exists) {
print('Docs: ${documentSnapshot.exists}');
int _userTotalMatchPerDay = 1;
print('No Data1');
await docRef
.set({
'userUid': userInfo[0],
'userName': userInfo[1],
'userEmail': userInfo[2],
'timeEnter': formattedDate,
'userTotalMatchPerDay': 1,
'accumulatedMatchScore': _matchScore,
'accumulatedGameScore': _gameScore,
})
.then((value) => print('Success'))
.catchError((error) => print("Failed to update user: $error"));
print('No Data2');
await docRef
.collection('scores')
.doc(formattedDate)
.set({
'userUid': userInfo[0],
'userName': userInfo[1],
'userEmail': userInfo[2],
'timeEnter': formattedDate,
'matchScore': _matchScore,
'gameScore': _gameScore,
})
.then((value) => print('Success'))
.catchError((error) => print("Failed to update user: $error"));
print('No Data3');
print(_userTotalMatchPerDay);
return _userTotalMatchPerDay;
} else {
print('No Data4');
// int newFollowerCount = snapshot.data()['followers'] + 1;
// Count Up Match # Per Day
int _userTotalMatchPerDay =
documentSnapshot['userTotalMatchPerDay'] + 1;
// Check Reach the Day Limit
if (_userTotalMatchPerDay < _maxMatchPerDay + 1) {
print('test 2');
// Update Total Doc
docRef.update({'userTotalMatchPerDay': _userTotalMatchPerDay});
// If Win (1) comes run this below. If not (0), don't run it
if (_matchScore == 1) {
print('test 3');
int accumulatedMatchScore =
documentSnapshot['accumulatedMatchScore'] + _matchScore;
docRef
.update({'accumulatedMatchScore': accumulatedMatchScore})
.then((value) => print('Success'))
.catchError((error) => print("Failed to update user: $error"));
}
// Update # of Game won
int accumulatedGameScore =
documentSnapshot['accumulatedGameScore'] + _gameScore;
docRef
.update({'accumulatedGameScore': accumulatedGameScore})
.then((value) => print('Success'))
.catchError((error) => print("Failed to update user: $error"));
print('No Data5');
await docRef
.collection('scores')
.doc(formattedDate)
.set({
'userUid': userInfo[0],
'userName': userInfo[1],
'userEmail': userInfo[2],
'timeEnter': formattedDate,
'matchScore': _matchScore,
'gameScore': _gameScore,
})
.then((value) => print('Success'))
.catchError((error) => print("Failed to update user: $error"));
print('No Data6');
}
print(_userTotalMatchPerDay);
return _userTotalMatchPerDay;
}
}).then((userTotalMatchPerDay) async {
print('userTotalMatchPerDay: $userTotalMatchPerDay');
print('formattedDate: $formattedDate');
if ((userTotalMatchPerDay) > 3) {
return userTotalMatchPerDay;
}
});
return null;
}
@override
Widget build(BuildContext context) {
return Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: DesignConfig.padding),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Match",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
],
),
),
),
);
}
}
</code></pre>
| 3 | 5,733 |
Exception while rendering XpsDocument after conversion from FlowDocument
|
<p>I'm developing an application that heavily uses the conversion from a FlowDocument to a XpsDocument. From time to time an exception is thrown:
NotSupportedException: "The URI prefix is not recognized."</p>
<p>My scenario is very complex and I condensed it to a simple test. If you type in some characters in the text box (fast), you'll get the exception immediately.</p>
<p>Xaml:</p>
<pre><code><Window x:Class="FlowDocPreview.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<RichTextBox Name="rtb" KeyUp="rtb_KeyUp" />
<DocumentViewer Grid.Column="1" Name="dv" />
</Grid>
</Window>
</code></pre>
<p>Code behind:</p>
<pre><code>using System;
using System.IO;
using System.IO.Packaging;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
namespace FlowDocPreview
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
rtb.Document = new FlowDocument();
}
Uri _packageUri = null;
private void rtb_KeyUp(object sender, KeyEventArgs e)
{
using (MemoryStream ms = new MemoryStream())
{
dv.Document = null;
if (_packageUri != null)
{
PackageStore.RemovePackage(_packageUri);
}
_packageUri = new Uri("memorystream://" + DateTime.Now.Ticks + ".xps");
TextRange sourceContent = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
MemoryStream stream = new MemoryStream();
sourceContent.Save(stream, DataFormats.Xaml);
FlowDocument flowDocumentCopy = new FlowDocument();
TextRange copyDocumentRange = new TextRange(flowDocumentCopy.ContentStart, flowDocumentCopy.ContentEnd);
copyDocumentRange.Load(stream, DataFormats.Xaml);
Package package = Package.Open(ms, FileMode.OpenOrCreate, FileAccess.ReadWrite);
PackageStore.AddPackage(_packageUri, package);
XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.SuperFast);
xpsDoc.Uri = _packageUri;
XpsDocumentWriter documentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
documentWriter.Write(((IDocumentPaginatorSource)flowDocumentCopy).DocumentPaginator);
dv.Document = xpsDoc.GetFixedDocumentSequence();
}
}
}
}
</code></pre>
<p>That exception cannot be catched (refer to <a href="https://social.msdn.microsoft.com/Forums/windows/en-US/431e8e80-3bf0-4679-a0c0-9b5cae4f2f38/systemnotsupportexception-the-uri-prefix-is-not-recognized-when-creating-xps-document?forum=netfxbcl" rel="nofollow">https://social.msdn.microsoft.com/Forums/windows/en-US/431e8e80-3bf0-4679-a0c0-9b5cae4f2f38/systemnotsupportexception-the-uri-prefix-is-not-recognized-when-creating-xps-document?forum=netfxbcl</a> ) or prevented in advance (the package seems to be existing correctly). I examined the .net code and found no reason for that strange behaviour. In total I've spent day or even weeks to find a fix.</p>
<p>Any ideas? Regards, Heady</p>
| 3 | 1,511 |
Error 500 for basic REST service in Lift Scala MongoDB while createRecord
|
<p>The REST service object code is: </p>
<pre><code>object Account extends RestHelper {
def createUser = {
for {
username <- S.param("username") ?~ "username parameter missing" ~> 400
number <- S.param("number") ?~ "number parameter missing"
} yield {
val u = GeoFence.createRecord.name(username)
u.save
u.asJSON
}
}
serve {
case Req("api" :: "hello" :: Nil, "json", GetRequest) => JString("hi")
case Req("api" :: "accounts" :: "new" :: Nil, "json", GetRequest) => createUser()
}
}
</code></pre>
<p>This is the exception I see on browser whenever I'm trying to run the REST service.</p>
<p>The exception is pointing to line 27 which is:</p>
<blockquote>
<p>val u = GeoFence.createRecord.name(username)</p>
<p>u.save</p>
</blockquote>
<p>HTTP ERROR 500</p>
<p>Problem accessing /api/accounts/new.json. Reason:</p>
<pre><code>(class: net/liftweb/record/Record$class, method: toForm signature: (Lnet/liftweb/record/Record;Lscala/Function1;)Lscala/xml/NodeSeq;) Incompatible object argument for function call
</code></pre>
<p>Caused by:</p>
<p>java.lang.VerifyError: (class: net/liftweb/record/Record$class, method: toForm signature: (Lnet/liftweb/record/Record;Lscala/Function1;)Lscala/xml/NodeSeq;) Incompatible object argument for function call
at smartfamily.model.GeoFence.(GeoFence.scala:21)
at smartfamily.model.GeoFence$.(GeoFence.scala:19)
at smartfamily.model.GeoFence$.(GeoFence.scala)
at smartfamily.api.Account$$anonfun$createUser$1$$anonfun$apply$1.apply(Account.scala:27)
at smartfamily.api.Account$$anonfun$createUser$1$$anonfun$apply$1.apply(Account.scala:25)
at net.liftweb.common.Full.map(Box.scala:478)
at smartfamily.api.Account$$anonfun$createUser$1.apply(Account.scala:25)
at smartfamily.api.Account$$anonfun$createUser$1.apply(Account.scala:24)
at net.liftweb.common.Full.flatMap(Box.scala:480)
at smartfamily.api.Account$.createUser(Account.scala:24)
at smartfamily.api.Account$$anonfun$1.apply(Account.scala:35)
at smartfamily.api.Account$$anonfun$1.apply(Account.scala:33)
at net.liftweb.http.rest.RestHelper$class.apply(RestHelper.scala:472)
at smartfamily.api.Account$.apply(Account.scala:21)
at smartfamily.api.Account$.apply(Account.scala:21)
at net.liftweb.util.NamedPF$$anonfun$applyBox$1.apply(NamedPartialFunction.scala:97)
at net.liftweb.util.NamedPF$$anonfun$applyBox$1.apply(NamedPartialFunction.scala:97)
at net.liftweb.common.Full.map(Box.scala:478)
at net.liftweb.util.NamedPF$.applyBox(NamedPartialFunction.scala:97)
at net.liftweb.http.LiftServlet.doService(LiftServlet.scala:220)
at net.liftweb.http.LiftServlet$$anonfun$doIt$1$1.apply$mcZ$sp(LiftServlet.scala:129)
at net.liftweb.http.LiftServlet$$anonfun$doIt$1$1.apply(LiftServlet.scala:129)
at net.liftweb.http.LiftServlet$$anonfun$doIt$1$1.apply(LiftServlet.scala:129)
at net.liftweb.util.TimeHelpers$class.calcTime(TimeHelpers.scala:344)
at net.liftweb.util.Helpers$.calcTime(Helpers.scala:34)
at net.liftweb.util.TimeHelpers$class.logTime(TimeHelpers.scala:353)
at net.liftweb.util.Helpers$.logTime(Helpers.scala:34)
at net.liftweb.http.LiftServlet.doIt$1(LiftServlet.scala:128)
at net.liftweb.http.LiftServlet.service(LiftServlet.scala:137)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2$$anonfun$apply$mcV$sp$1.apply$mcV$sp(HTTPProvider.scala:69)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2$$anonfun$apply$mcV$sp$1.apply(HTTPProvider.scala:68)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2$$anonfun$apply$mcV$sp$1.apply(HTTPProvider.scala:68)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.URLRewriter$.doWith(Req.scala:1063)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2.apply$mcV$sp(HTTPProvider.scala:67)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2.apply(HTTPProvider.scala:67)
at net.liftweb.http.provider.HTTPProvider$$anonfun$service$2.apply(HTTPProvider.scala:67)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.provider.HTTPProvider$class.service(HTTPProvider.scala:63)
at net.liftweb.http.LiftFilter.service(LiftServlet.scala:689)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(ServletFilterProvider.scala:67)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1$$anonfun$apply$mcV$sp$1.apply(ServletFilterProvider.scala:62)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1$$anonfun$apply$mcV$sp$1.apply(ServletFilterProvider.scala:62)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13$$anonfun$apply$14$$anonfun$apply$15.apply(Vars.scala:513)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13$$anonfun$apply$14.apply(Vars.scala:512)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13.apply(Vars.scala:511)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12.apply(Vars.scala:510)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$class.apply(Vars.scala:509)
at net.liftweb.http.RequestVarHandler$.apply(Vars.scala:428)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1.apply$mcV$sp(ServletFilterProvider.scala:61)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1.apply(ServletFilterProvider.scala:61)
at net.liftweb.http.provider.servlet.ServletFilterProvider$$anonfun$doFilter$1.apply(ServletFilterProvider.scala:61)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13$$anonfun$apply$14$$anonfun$apply$15.apply(Vars.scala:513)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13$$anonfun$apply$14.apply(Vars.scala:512)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12$$anonfun$apply$13.apply(Vars.scala:511)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$$anonfun$apply$12.apply(Vars.scala:510)
at net.liftweb.util.ThreadGlobal.doWith(ThreadGlobal.scala:71)
at net.liftweb.http.CoreRequestVarHandler$class.apply(Vars.scala:509)
at net.liftweb.http.TransientRequestVarHandler$.apply(Vars.scala:432)
at net.liftweb.http.provider.servlet.ServletFilterProvider$class.doFilter(ServletFilterProvider.scala:60)
at net.liftweb.http.LiftFilter.doFilter(LiftServlet.scala:689)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:926)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)</p>
<p><strong>UPDATE 1</strong></p>
<p>Well it was resolved by the excellent lift community at the given link. </p>
<p><a href="http://groups.google.com/group/liftweb/browse_thread/thread/e70cc3763734fdd9" rel="nofollow">http://groups.google.com/group/liftweb/browse_thread/thread/e70cc3763734fdd9</a></p>
| 3 | 3,405 |
Writing to Docker Filesystem as non-root, non-privileged user
|
<p>I have a node/docker app that runs some scripts, and downloads a file to the docker fs, which is then sent to an FTP server. The file is saved to the filesystem in a folder that resides in the same directory (app/src) as the node scripts, allowing easy access for the scripts to then ftp the file. Currently, the scripts are only able to download the file when the image is run as root user, with the --privileged flag. I want to production-ize this and deploy it (ideally on Heroku). Heroku does not allow images to be run as root afaik.</p>
<p>Changing the user to non-root causes the file to not be downloaded, though the container is built perfectly fine, and the image runs with no errors thrown. Seems to be a permissions issue.</p>
<p>Is there a way I can modify this so that I can run this as non-root user and still get the file into the filesystem? The scripts run a headless chrome browser that crawls a website and clicks a button to download an xls file. ( I have the non-privileged user commented out and root user uncommented here, just so I can switch back and forth when testing)</p>
<p>Dockerfile</p>
<pre><code>FROM node:latest
# update and add all the steps for running with xvfb
RUN apt-get update &&\
apt-get install -yq gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 \
libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 \
libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 \
libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \
ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget \
xvfb x11vnc x11-xkb-utils xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic x11-apps \
&& apt-get install -y wget gnupg \
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
#remove zombie images
ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_x86_64 /usr/local/bin/dumb-init
RUN chmod +x /usr/local/bin/dumb-init
ENTRYPOINT ["dumb-init", "--"]
# add the required dependencies
WORKDIR /app
# COPY node_modules /app/node_modules
RUN npm install puppeteer \
# Add user so we don't need --no-sandbox.
# same layer as npm install to keep re-chowned files from using up several hundred MBs more space
&& groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \
&& mkdir -p /home/pptruser/Downloads \
&& chown -R pptruser:pptruser /home/pptruser \
&& npm install express \
&& npm install basic-ftp
# && chown -R pptruser:pptruser /node_modules
EXPOSE 3000
# Run everything after as non-privileged user.
# USER pptruser
USER root
# Finally copy the build application
COPY . .
# make sure we can run without a UI
ENV DISPLAY :99
CMD Xvfb :99 -screen 0 1024x768x16 -nolisten unix & node server.js
</code></pre>
<p>Here are permissions for /app</p>
<pre><code>root@d5c51850b0b7:/app# ls -al
total 92
drwxr-xr-x 1 root root 4096 Dec 8 17:24 .
drwxr-xr-x 1 root root 4096 Dec 9 17:05 ..
-rw-r--r-- 1 root root 6148 Dec 7 18:00 .DS_Store
-rw-r--r-- 1 root root 41 Dec 7 17:26 .dockerignore
-rw-r--r-- 1 root root 46 Dec 7 18:53 .env
drwxr-xr-x 7 root root 4096 Dec 7 18:02 .git
-rw-r--r-- 1 root root 1610 Dec 7 18:01 .gitignore
-rw-r--r-- 1 root root 2120 Dec 8 17:24 Dockerfile
-rw-r--r-- 1 root root 950 Dec 7 21:50 Readme.md
-rw-r--r-- 1 root root 140 Dec 7 21:46 docker-compose.yml
drwxr-xr-x 102 root root 4096 Dec 4 17:10 node_modules
-rw-r--r-- 1 root root 32485 Dec 7 19:36 package-lock.json
-rw-r--r-- 1 root root 307 Dec 7 19:36 package.json
-rw-r--r-- 1 root root 262 Dec 8 17:21 server.js
drwxr-xr-x 2 root root 4096 Dec 7 17:26 src
</code></pre>
| 3 | 1,665 |
Images not loading while building my nuxt app locally
|
<p><strong>Issue:-</strong> Images was not loading while building my nuxt app it worked well when I deployed it to netlify and in my other machine image was load correctly but one JS file did not load and it is related to one package</p>
<p><strong>Structure</strong></p>
<ul>
<li>assets
<ul>
<li>Fonts</li>
<li>Images</li>
</ul>
</li>
<li>pages
<ul>
<li>index.vue</li>
</ul>
</li>
<li>static
<ul>
<li>favicon.ico</li>
</ul>
</li>
<li>vues
<ul>
<li>// all the components</li>
</ul>
</li>
<li>.editorconfig</li>
<li>nuxt.config.js</li>
<li>package.json</li>
</ul>
<p><code>nuxt.config.js</code></p>
<pre class="lang-js prettyprint-override"><code>export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'test-app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
ssr: true,
target: "static",
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
],
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
babel: {
compact: true,
}
}
}
</code></pre>
<p><code>package.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
"name": "test-app",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"@babel/polyfill": "^7.11.5",
"@babel/preset-env": "^7.12.17",
"bootstrap": "^4.6.0",
"bootstrap-vue": "^2.21.2",
"core-js": "^3.15.1",
"nuxt": "^2.15.7",
"mutationobserver-shim": "^0.3.7",
"popper.js": "^1.16.1",
"portal-vue": "^2.1.7",
"vue-slick-carousel": "^1.0.6"
},
"devDependencies": {
"node-sass": "^6.0.1",
"sass": "^1.26.11",
"sass-loader": "^10.2.0",
"vue-cli-plugin-bootstrap-vue": "~0.8.2"
}
}
</code></pre>
| 3 | 1,465 |
hibernate - foreign key constraints fails even after child records are deleted prior to the parent records
|
<p>I have Two beans AgeGroupDetails and organizationDetails. We have organizationDetails primary key as a foriegn key in the ageGroupDetails table. I am deleting the ageGroupDetails table recored based on organizationId and then deleting organizationDetails table record based on organizationId. I have checked the logs the delete statement related to the ageGroupDetails deletion is executed,(I think not all rows are deleted, how to make sure all rows are deleted) and while deleting organizationdetails record it is throwing foriegn key constraints fails. I have tried different ways to avoid the problem like setting the flushmode to auto so that one statement gets flushed before another statement gets executed and also tried to flush using entityManager.flush() method but of no use. Some times the delete statement generated by hiberante is not executed and raising an exception. I want a solution in that case also</p>
<p>AgeGroupDetails.java</p>
<pre><code>public class AgeGroupDetails implements Identifiable<Long>, Serializable, Copyable<AgeGroupDetails> {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "age_group_id", precision = 19)
private Long ageGroupId; // pk
@Column(name = "organization_id", nullable=false, insertable = false, updatable = false)
private Integer organizationId; // not null
@JsonIgnore
@NotNull
@Cache(usage = NONSTRICT_READ_WRITE)
@JoinColumn(name = "organization_id", nullable = false)
@ManyToOne(cascade = PERSIST, fetch = LAZY)
private OrganizationDetails organizationDetails;
@JsonIgnore
@NotNull
@Cache(usage = NONSTRICT_READ_WRITE)
@JoinColumn(name = "updated_by", nullable = false)
@ManyToOne(cascade = PERSIST, fetch = LAZY)
private MemberDetails updatedByMember;
// getters and setters
</code></pre>
<p>OrganizationDetails.java</p>
<p>no ageGroup related variable in organization details</p>
<h2>data about age_Group_details table</h2>
<pre><code> CONSTRAINT `FK_age_group_details_member_details1` FOREIGN KEY (`updated_by`) REFERENCES `member_details` (`member_id`),
CONSTRAINT `FK_age_group_details_organization_details1` FOREIGN KEY (`organization_id`) REFERENCES `organization_details` (`organization_id`)
) ENGINE=InnoDB AUTO_INCREMENT=800 DEFAULT CHARSET=latin1
</code></pre>
<p>I am deleting the object using</p>
<pre><code>entityManager.remove(entity);
</code></pre>
<p>I am getting the following exception</p>
<pre><code> 2021-03-03T18:24:36,887 - DEBUG [https-openssl-nio-8443-exec-13] - revanthgulla -
/* delete com.viprasi.domain.OrganizationDetails */ delete
from
organization_details
where
organization_id=? - LOCAL
2021-03-03T18:24:36,910 - WARN [https-openssl-nio-8443-exec-13] - revanthgulla - SQL Error: 1451, SQLState: 23000 - LOCAL
2021-03-03T18:24:36,910 - ERROR [https-openssl-nio-8443-exec-13] - revanthgulla - Cannot delete or update a parent row: a foreign key constraint fails (`thapos_db_dev`.`age_group_details`, CONSTRAINT `FK_age_group_details_organization_details1` FOREIGN KEY (`organization_id`) REFERENCES `organization_details` (`organization_id`)) - LOCAL
2021-03-03T18:24:36,913 - ERROR [https-openssl-nio-8443-exec-13] - revanthgulla - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement] - LOCAL
2021-03-03T18:24:37,476 - ERROR [https-openssl-nio-8443-exec-13] - revanthgulla - OrganizationDetailsControllerWithPathVariable: Exception occured while deleting organization - LOCAL
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259) ~[spring-orm-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:225) ~[spring-orm-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:540) ~[spring-orm-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:742) ~[spring-tx-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:710) ~[spring-tx-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:532) ~[spring-tx-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304) ~[spring-tx-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at com.sun.proxy.$Proxy1104.deleteOrganization(Unknown Source) ~[?:?]
at com.viprasi.web.controller.OrganizationDetailsControllerWithPathVariable.delete(OrganizationDetailsControllerWithPathVariable.java:327) [classes/:?]
at com.viprasi.web.controller.OrganizationDetailsControllerWithPathVariable$$FastClassBySpringCGLIB$$3becd113.invoke(<generated>) [classes/:?]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685) [spring-aop-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at com.viprasi.web.controller.OrganizationDetailsControllerWithPathVariable$$EnhancerBySpringCGLIB$$8ce6a8f3.delete(<generated>) [classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_271]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_271]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.web.filter.ShallowEtagHeaderFilter.doFilterInternal(ShallowEtagHeaderFilter.java:108) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129) [sitemesh-2.4.2.jar:?]
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77) [sitemesh-2.4.2.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:185) [spring-orm-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.switchuser.SwitchUserFilter.doFilter(SwitchUserFilter.java:197) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:84) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:155) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:157) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:185) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:467) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311) [catalina.jar:8.5.23]
at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213) [urlrewritefilter-4.0.4.jar:4.0.4]
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171) [urlrewritefilter-4.0.4.jar:4.0.4]
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) [urlrewritefilter-4.0.4.jar:4.0.4]
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) [urlrewritefilter-4.0.4.jar:4.0.4]
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389) [urlrewritefilter-4.0.4.jar:4.0.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.switchuser.SwitchUserFilter.doFilter(SwitchUserFilter.java:197) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:155) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:157) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:8.5.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:8.5.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:8.5.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [catalina.jar:8.5.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [catalina.jar:8.5.23]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) [catalina.jar:8.5.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [catalina.jar:8.5.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [catalina.jar:8.5.23]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-coyote.jar:8.5.23]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:8.5.23]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-coyote.jar:8.5.23]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-coyote.jar:8.5.23]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:8.5.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_271]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624
</code></pre>
<p>I could not give the complete exception due to body size limitation.please help</p>
| 3 | 10,743 |
ConnectionException when running a Oozie workflow
|
<p>When trying to run a Oozie workflow with a Java action, I get the following error.</p>
<pre><code>JA006: Call From sandbox.hortonworks.com/10.0.2.15 to sandbox.hortonworks.com:10020 failed
on connection exception: java.net.ConnectException: Connection refused;
For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
</code></pre>
<p>This is the workflow.xml</p>
<pre><code><workflow-app name="cascading-wordcount" xmlns="uri:oozie:workflow:0.4">
<start to="wordcount_job"/>
<action name="wordcount_job">
<java>
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<configuration>
<property>
<name>jobTracker</name>
<value>sandbox.hortonworks.com:8050</value>
</property>
</configuration>
<main-class>com.test.cascading.WordCount</main-class>
<arg>/user/hue/oozie/test/cascading-in/rain.txt</arg>
<arg>/user/hue/oozie/test/cascading-out</arg>
<capture-output/>
</java>
<ok to="end"/>
<error to="kill"/>
</action>
<kill name="kill">
<message>Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
</kill>
<end name="end"/>
</code></pre>
<p></p>
<p>I can't even view the logs related to the job. When I try, it gives </p>
<pre><code>Could not find job job_1453962161829_0005.
Job job_1453962161829_0005 could not be found: HTTPConnectionPool(host='sandbox.hortonworks.com', port=19888): Max retries exceeded with url: /ws/v1/history/mapreduce/jobs/job_1453962161829_0005 (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
</code></pre>
<p>I can run the same jar used here using CLI with the command <code>yarn jar</code>. I'm a novice to these. I fear I might have done a stupid mistake.</p>
<p><strong>EDIT</strong></p>
<p>This is what I get when trying to view the logs through CLI as snies said.</p>
<pre><code>impl.TimelineClientImpl: Timeline service address: http://sandbox.hortonworks.com:8188/ws/v1/timeline/
client.RMProxy: Connecting to ResourceManager at sandbox.hortonworks.com/10.0.2.15:8050
/app-logs/root/logs/application_1453962161829_0005 does not exist.
Log aggregation has not completed or is not enabled.
</code></pre>
| 3 | 1,059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.