input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Get prepared statements list in mysql <p>As <a href="https://dev.mysql.com/doc/refman/5.5/en/sql-syntax-prepared-statements.html" rel="nofollow">this</a> document says prepared statements are server side statements like functions or procedures (correct me if I'm wrong).</p>
<p>But I have some trouble finding defined prepared statement on my database. I'm currently working with <code>MySQL Workbench</code> and in the left side pane I can see all my procedures and functions and I can't see any of defined prepared statements here.</p>
<p>So is there any query which I can use to get their names?</p>
| <p>The doc says</p>
<blockquote>
<p>A prepared statement is specific to the session in which it was created. If you terminate a session without deallocating a previously prepared statement, the server deallocates it automatically.</p>
</blockquote>
<p>So Prepared Statements get deleted automtically after the session ends. Besides, a Prepared Statement does not have a name It is just a query string.</p>
|
SQL get time values between a time range <p>I have to calculate all the time values which are between a particular start time and end time on the basis of a particular time interval on a date in stored procedure in SQL.</p>
<p>I have 4 parameters for my stored procedure.</p>
<pre><code>@date_value nvarchar(1000),//date value'2016-10-09'
@starttime TIME(0) //= '08:00',//suppose starttime is 8am
@endtime TIME(0) //= '13:00'
@interval INT //= '20' //20 minutes
</code></pre>
<p>I am trying to get all the time values between the starttime and endtime. I need it like this.
8:00,8:20,08:40........upto 12:50(end value I dont need).</p>
<p>I have googled it and found that we can use</p>
<pre><code>SELECT DATEADD(MINUTE, @MinutesToAdd, @StartTime)
</code></pre>
<p>Here I am not able to include the end time.Please help me</p>
| <pre><code>Declare
@date_value nvarchar(1000)='2016-10-09',
@starttime TIME(0)= '08:00',
@endtime TIME(0) = '13:00',
@interval INT = '20'
;With cte(stime)
as
(
SELECT
cast(cast( @date_value as datetime)
+ CONVERT(CHAR(8), @starttime, 108) as time)
union all
select
cast(dateadd(minute,@interval,stime) as time)
from cte
where cast(dateadd(minute,@interval,stime) as time)<@endtime
)
select * from cte
</code></pre>
|
How to wait on sequelize executing a findOne <p>I've got a route using Sequelize.js</p>
<pre><code>app.get('/api/users/:username', (req, res) => {
const foundUser = getUserByUsername(req.params.username);
console.log(`foundUser = ${foundUser}`);
return res.send(foundUser);
});
</code></pre>
<p>the getUserByUsername function is as follows</p>
<pre><code>const getUserByUsername = username => {
Viewer.findOne({
where: {username}
}).then(response => {
console.log(response.dataValues);//the object with the data I need
return response.dataValues;
});
};
</code></pre>
<p>I hoped on getting the object in my const foundUser in my route, but it seems I need to wait until the findOne has been executed, because in my console I can see that the log of foundUser (which is undefined then) is executed before the function getUserByUsername</p>
<pre><code>foundUser = undefined
Executing (default): SELECT `id`, `username`, `instakluiten`, `role`, `createdAt`, `updatedAt` FROM `viewers` AS `viewer` WHERE `viewer`.`username` = 'instak' LIMIT 1;
{ id: 19,
username: 'instak',
instakluiten: 18550,
role: 'moderators',
createdAt: 2016-10-02T16:27:44.000Z,
updatedAt: 2016-10-09T10:17:40.000Z }
</code></pre>
<p>How can I make sure that my foundUser will be updated with the data áfter the user has been found?</p>
| <pre><code>app.get('/api/users/:username', (req, res) => {
getUserByUsername(req.params.username, function(err, result){
const foundUser = result;
console.log(`foundUser = ${foundUser}`);
res.send(foundUser);
});
});
const getUserByUsername = function(username, callback) {
Viewer.findOne({
where: {username}
}).then(response => {
console.log(response.dataValues);//the object with the data I need
return callback(null, response.dataValues);
});
};
</code></pre>
|
Python - Concatenating <p>I'm going crazy with the following code which should be really easy but doesn't work :/</p>
<pre><code>class Triangulo_String:
_string = ''
_iteraciones = 0
_string_a_repetir = ''
def __init__(self, string_a_repetir, iteraciones):
self._string_a_repetir = string_a_repetir
self._iteraciones = iteraciones
def concatenar(self):
for i in range(0, self._iteraciones, 1):
self._string = self._string_a_repetir + self._string + '\n'
</code></pre>
<p>I'm initializing <code>_iteraciones</code> to <code>3</code> and <code>_string_a_repetir</code> to <code>'*'</code></p>
<p>And the output is just: </p>
<pre><code>***
</code></pre>
<p>When I'm expecting:</p>
<pre><code>*
**
***
</code></pre>
<p>I've debugged it and when doing the concatenating it just concatenates the self._string_a_repetir, not the _string nor the line break.</p>
<p>Such an easy thing is driving me crazy ._.</p>
| <p>The relevant bit is in this part:</p>
<pre><code>for i in range(0, self._iteraciones, 1):
self._string = self._string_a_repetir + self._string + '\n'
</code></pre>
<p>Letâs go through the iterations one by one:</p>
<pre><code># Initially
_string = ''
_string_a_repetir = '*'
_iteraciones = 3
# i = 0
_string = _string_a_repetir + _string + '\n'
= '*' + '' + '\n'
= '*\n'
# i = 1
_string = _string_a_repetir + _string + '\n'
= '*' + '*\n' + '\n'
= '**\n\n'
# i = 2
_string = _string_a_repetir + _string + '\n'
= '*' + '**\n\n' + '\n'
= '***\n\n\n'
</code></pre>
<p>As you can see, this is totally expected to happen, since you never repeat that character more than once per line. And you are also incorrectly concatenating the previous string with the new string (placing it in between the current lineâs text and its line break).</p>
<p>What you are looking for is something like this:</p>
<pre><code>for i in range(0, self._iteraciones, 1):
self._string = self._string + (self._string_a_repetir * (i + 1)) + '\n'
</code></pre>
<p>The <code>string * number</code> works to repeat the <code>string</code> for <code>number</code> times.</p>
<hr>
<p>As a general note, you should not use those class members that way:</p>
<pre><code>class Triangulo_String:
_string = ''
_iteraciones = 0
_string_a_repetir = ''
</code></pre>
<p>This will create those members as <em>class</em> variables, which are shared across all its instances. This is not directly a problem if you never change the class members but it could cause confusion later. You should instead initialize all instance attributes inside the <code>__init__</code>:</p>
<pre><code>class Triangulo_String:
def __init__(self, string_a_repetir, iteraciones):
self._string = ''
self._string_a_repetir = string_a_repetir
self._iteraciones = iteraciones
</code></pre>
|
How to select string between characters? <p>I made this table:</p>
<p>Table (Websites)</p>
<pre><code>WebsiteID | WebsiteName
2324442 'http://www.samsung.com/us/'
2342343 'https://www.microsoft.com/en-au/windows/'
3242343 'http://www.apple.com/au/iphone/'
</code></pre>
<p>And I want to be able to <code>SELECT</code> the domain names from this table.</p>
<p>Something like this:</p>
<pre><code>WebsiteName
'www.samsung.com'
'www.microsoft.com'
'www.apple.com'
</code></pre>
<p>Is there a string method I can use for this? Like splitting the string between <code>//</code> and <code>/</code>. </p>
| <p>You can use <code>SUBSTRING_INDEX()</code> :</p>
<pre><code>SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(websiteName, '//', -1),
'/', 1)
FROM table
</code></pre>
|
How to send PUT request with a file and an array of data in Laravel <p>I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.</p>
<p>Please see the code below :</p>
<p>web.php ( route )</p>
<pre><code>Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController@update');
});
</code></pre>
<p>My angularjs product service :</p>
<pre><code>function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
</code></pre>
<p>My ProductController update function </p>
<pre><code>public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
</code></pre>
<p>This is what I see in Chrome inspectmen
<a href="http://i.stack.imgur.com/ftwJd.png" rel="nofollow"><img src="http://i.stack.imgur.com/ftwJd.png" alt="Put header"></a><a href="http://i.stack.imgur.com/nQUpB.png" rel="nofollow"><img src="http://i.stack.imgur.com/nQUpB.png" alt="Sended data"></a>
<a href="http://i.stack.imgur.com/ho4lR.png" rel="nofollow"><img src="http://i.stack.imgur.com/ho4lR.png" alt="Result was empty"></a></p>
<p>Please share your experiences on this problem. Thanks.</p>
| <p>Try this method:</p>
<pre><code>public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
</code></pre>
<p>Also, make sure you're using <code>Route::put</code> or <code>Route::resource</code> for your route.</p>
|
add another timer on already running loop <p>Given the following program - </p>
<pre><code>#include <iostream>
#include <uv.h>
int main()
{
uv_loop_t loop;
uv_loop_init(&loop);
std::cout << "Libuv version: " << UV_VERSION_MAJOR << "."
<< UV_VERSION_MINOR << std::endl;
int r = 0;
uv_timer_t t1_handle;
r = uv_timer_init(&loop, &t1_handle);
uv_timer_start(&t1_handle,
[](uv_timer_t *t) { std::cout << "Timer1 called\n"; }, 0, 2000);
uv_run(&loop, UV_RUN_DEFAULT);
// second timer
uv_timer_t t2_handle;
r = uv_timer_init(&loop, &t2_handle);
uv_timer_start(&t2_handle,
[](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0, 1000);
uv_loop_close(&loop);
}
</code></pre>
<p>The second timer handle is never run on the loop, since the loop is already running, and "Timer2 called" is never printed. So I tried stopping the loop temporarily after running it and then adding the second timer - </p>
<pre><code>....
uv_run(&loop, UV_RUN_DEFAULT);
// some work
uv_stop(&loop);
// now add second timer
uv_run(&loop, UV_RUN_DEFAULT); // run again
....
</code></pre>
<p>But this again didn't work, probably because the later lines won't be executed after 1st loop starts running with an repeating timer. So how should I add a new timer handle to already running uvloop? </p>
| <p>You are right that loop needs to be stopped before it can register a new handle. It cannot be achieved by calling <code>uv_stop</code> function right after <code>uv_run</code>, because <code>uv_run</code> needs to return first. It can be achieved for example by stopping it using a handle callback. Here is quite silly example of how it can be done using the existing Timer1 handle. It stops the loop exactly one time on the first run.</p>
<pre><code>#include <iostream>
#include <uv.h>
int main() {
uv_loop_t loop;
uv_loop_init(&loop);
std::cout << "Libuv version: " << UV_VERSION_MAJOR << "." << UV_VERSION_MINOR
<< std::endl;
int r = 0;
uv_timer_t t1_handle;
r = uv_timer_init(&loop, &t1_handle);
*(bool *)t1_handle.data = true; // need to stop the loop
uv_timer_start(&t1_handle,
[](uv_timer_t *t) {
std::cout << "Timer1 called\n";
bool to_stop = *(bool *)t->data;
if (to_stop) {
std::cout << "Stopping loop and resetting the flag\n";
uv_stop(t->loop);
*(bool *)t->data = false; // do not stop the loop again
}
},
0, 2000);
uv_run(&loop, UV_RUN_DEFAULT);
std::cout << "After uv_run\n";
// second timer
uv_timer_t t2_handle;
r = uv_timer_init(&loop, &t2_handle);
uv_timer_start(&t2_handle,
[](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0,
1000);
std::cout << "Start loop again\n";
uv_run(&loop, UV_RUN_DEFAULT);
uv_loop_close(&loop);
}
</code></pre>
<p>So the output is</p>
<pre><code>Libuv version: 1.9
Timer1 called
Stopping loop and resetting the flag
After uv_run
Start loop again
Timer2 called
Timer2 called
Timer1 called
Timer2 called
Timer2 called
Timer1 called
</code></pre>
|
Swift Storyboard List view Not Working? <p>Been following tutorials online to create a scrollable list view in the storyboard.</p>
<p>I have done the following</p>
<p>View Controller --> Scroll View --> Content View</p>
<p>The scroll view is constrained to the View controller.
The content view width is constrained to the View controller.</p>
<p>The contentSize is set to 1000 height for the content view.
The story board is set to 1000 height.
The scroll view is set to 1000 height.</p>
<p>It appears to only scroll down half way</p>
<p>Any ideas on what i have done wrong here</p>
<p>Thank you</p>
| <p>try to remove the height constraint for the scrollview, and fix it to the bottom of your parent view.</p>
|
VS2015 with sdl2 error : "#using needs c++/cli mode enabled" <p>I've been trying to follow lazy foo's productions tutorial on sdl2 and I keep on running into the same issue. I made a template that links to the correct files and all and it worked for a while. But now when I create a project and include iostream for example, it tells me #using need c++/cli mode enabled.</p>
<p>So I then tried enabling it in the project settings but then it gave another error : "Cannot open metadata file iostream"</p>
<p>I tried :
Rebuilding the project and solution</p>
<p>Cleaning the project and solution</p>
<p>I read this question and its answers : <a href="http://stackoverflow.com/questions/20490857/visual-studio-getting-error-metadata-file-xyz-could-not-be-found-after-edi">Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue</a></p>
<p>Tried this too : <a href="http://stackoverflow.com/questions/4969325/intellisense-using-requires-c-cli-to-be-enabled">IntelliSense: "#using" requires C++/CLI to be enabled</a></p>
<p>All of the above did not work</p>
| <p>Don't confuse <code>#include</code>, <code>using</code> and <code>#using</code>. </p>
<p><code>#using</code> is used to import class libraries in C++/CLI, which is something you won't ever need unless you work with .NET libraries (but then usually you are better off just using C#, unless you are writing interop code). </p>
<p><code>#include</code> is for including header files, which is what you normally do in "regular" C++. <code><iostream></code> is a regular standard library header, so you need <code>#include</code> (as in <code>#include <iostream></code>).</p>
<p><code>using</code> instead is used to bring names in the current scope (either the whole content of a namespace - as in the dreaded <code>using namespace std;</code>) or single names (as in <code>using std::cout;</code>). From C++11 it's also used to enable constructors inheritance and to create type aliases, but for the moment I don't think you need to worry about these uses. </p>
<p>But most importantly: please take the time to <em>first</em> learn the basics of the language from reputable sources before trying random stuff. All this <code>#using</code> mess wouldn't have arisen if you even just looked first at the classic hello would example you can find everywhere on the Internet. </p>
|
How to customize the payload section of the JWT response <p>What do I need to do to customize the <code>url(r'^auth/login/', obtain_jwt_token)</code> view to allow me to add data to the JWT token</p>
<p>I have a django-rest-framework API that is used by independent web applications. What I want is to return to the web app the logged in user's role and permissions together with what djangorestframework-jwt already returns.</p>
<p>I already have the roles in a python dictionary but I can't figure out what is required to override the default payload. </p>
<p>user_payload = {'user': user, 'roles': roles}</p>
<p>I thought it was as simple as replacing the 'user' in <code>payload = jwt_payload_handler(user)</code> with my user_payload but then am getting serializer errors. Is there a cleaner/easier way to do it? </p>
<p>djangorestframework==3.4.7, djangorestframework-jwt==1.8.0</p>
| <p><strong>JWT_RESPONSE_PAYLOAD_HANDLER</strong>
Responsible for controlling the response data returned after login or refresh. Override to return a custom response such as including the serialized representation of the User.</p>
<p>Defaults to return the JWT token.</p>
<p>Example:</p>
<pre><code>def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user).data
}
</code></pre>
<p>Default is <code>{'token': token}</code></p>
|
autocomplete jQuery.noConflict <p>I want to add a new autocomplete input to an existing page, that already uses a bundled version of jQuery. Therefore I need to use <code>jQuery.noConflict()</code>.</p>
<p>Outside of this page my code works fine, but on the existing page I don't know how to get it to work.</p>
<p>I always get an Error <code>$ (...).autocomplete is not a function</code>.</p>
<p>Here the code I use:</p>
<pre><code>// .....code from existing page with already loaded jQuery script
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
$.noConflict();
jQuery( document ).ready(function( $ ) {
/* Make the AJAX request once for the source array: */
$.getJSON("./mapdata/get_list_json.php", function (data) {
$("#parzelle").autocomplete({
minLength: 3,`enter code here`
source: data,
dataType: "json",
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox and hidden field
$(this).val(ui.item.label);
$("#gid").val(ui.item.value);
}
});
});
});
</code></pre>
| <p>Sorry, but I did also e few changings to the code.
So here is how I get it to work:</p>
<pre><code><script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
// .....code from existing page with already loaded jQuery script
$J = jQuery.noConflict();
$J( document ).ready(function( $J ) {
//$(function () {
/* Make the AJAX request once for the source array: */
$J.getJSON("./mapdata/get_parzellen_list_json.php", function (data) {
$J("#parzelle").autocomplete({
minLength: 3,
source: data,
dataType: "json",
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox and hidden field
$J(this).val(ui.item.label);
$J("#gid").val(ui.item.value);
}
});
});
});
</code></pre>
|
Display:none or visibility:hidden on body element on page load - does it affect SEO? <p>I am building a web page and I do some JS calculations and styling to make fancy things. However, I am stuck with <a href="https://en.wikipedia.org/wiki/Flash_of_unstyled_content" rel="nofollow">FOUC</a>. First I call the required styles, then depending on JS calculations I change some paddings and margins on divs. This leads to some kind of flashing of the page. To ommit this, I want to set <code>display:none</code> or <code>visibility:hidden</code> to the <code>body</code> element until the calculations are done, then show the page.</p>
<p><strong>HTML</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<!-- These meta tags come first. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Theme Example</title>
<!-- Bootstrap -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/styles.css" rel="stylesheet">
<script src="assets/js/modernizr-custom.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('body').hide();
// ... do calculations and styling ...
$('body').show();
</script>
</head>
</code></pre>
<p>Do this affect SEO? Any other ways of getting around that problem?</p>
| <p>As long as you are not hiding keywords or spamming with content there should be no issue. </p>
<p>For more you can check this topic on <a href="https://productforums.google.com/forum/?hl=en#!category-topic/webmasters/crawling-indexing--ranking/9IJHC83yge8" rel="nofollow">Google Webmaster Central</a> forum:</p>
<blockquote>
<p>"Merely using display:none will not automatically trigger a penalty.
The key is whether or not there is a mechanism - either automatic or
one that is invoked by the user - to make the content visible.Google
is becoming very adept at processing JavaScript to find and interpret
such mechanisms.If you use valid HTML, CSS, and JavaScript you have
nothing to worry about. Good luck!"</p>
</blockquote>
<p>Hope this helps.</p>
|
Passing data from activity to fragment causes "ScrollView can host only one direct child" error <p>I am making an app using <a href="http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/" rel="nofollow">this</a> tutorial. I made some changes in my code, ie I wanted to get data from server to my main activity and pass it to my fragments. Before that , when I would open the app it worked perfectly, bu now it crashes. <strong><em>I have tried a bunch of answers from stackoverflow</em></strong> (<a href="http://stackoverflow.com/questions/6528612/android-scrollview-can-host-only-one-direct-child">1</a>, <a href="http://stackoverflow.com/questions/20081217/java-lang-illegalstateexception-scrollview-can-host-only-one-direct-child">2</a>, <a href="http://stackoverflow.com/questions/3735095/how-can-i-avoid-illegalstateexception-scrollview-can-host-only-one-direct-chil">3</a>, <a href="http://stackoverflow.com/questions/16699772/scrollview-can-host-only-one-direct-child">4</a>, <a href="http://stackoverflow.com/questions/3734296/how-do-i-add-scrolling-to-an-android-layout">5</a>...) <strong><em>before asking a question, but none of them answered my question.</em></strong> When I was getting restaurants from fragment directly it worked perfectly but passing the data from the activity causes this error. </p>
<p>Main Activity (I pass get data from server and pass it to fragment):</p>
<pre><code>TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_map)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_list)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_my_list)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
RestaurantsFragment restaurantsFragment = new RestaurantsFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("restaurantList", (ArrayList<? extends Parcelable>) restaurantList);
restaurantsFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.sliding_tabs, restaurantsFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
</code></pre>
<p>Restaurant Fragment (I do get data from my main activity, I get the restaurants from the server when I debug):</p>
<pre><code>public class RestaurantsFragment extends Fragment {
private static final String TAG = RestaurantsFragment.class.getSimpleName();
// Restaurants json url
private ProgressDialog pDialog;
private ArrayList restaurantList = new ArrayList<>();
private ListView listView;
private CustomListAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_restaurants, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
restaurantList = bundle.getParcelableArrayList ("restaurantList");
}
listView = (ListView) view.findViewById(R.id.restaurants_list);
adapter = new CustomListAdapter(getActivity(), restaurantList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
return view;
}
</code></pre>
<p>fragment_restaurants</p>
<pre><code><RelativeLayout 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=".sliderfragments.RestaurantsFragment">
<ListView
android:id="@+id/restaurants_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_row_selector" />
</RelativeLayout>
</code></pre>
<p>list_row</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_row_selector"
android:padding="8dp">
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/thumbnail"
android:background="@drawable/default_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- User Name -->
<TextView
android:id="@+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/thumbnail"
android:layout_toRightOf="@+id/thumbnail"
android:textSize="@dimen/userName"
android:textStyle="bold" />
<!-- Date -->
<TextView
android:id="@+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/userName"
android:layout_marginTop="1dip"
android:layout_toRightOf="@+id/thumbnail"
android:textSize="@dimen/date" />
<!-- Time -->
<TextView
android:id="@+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/date"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/thumbnail"
android:textColor="@color/time"
android:textSize="@dimen/time" />
</RelativeLayout>
</code></pre>
<p>content_main</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/app_bar_main">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="@android:color/white" />
</android.support.design.widget.AppBarLayout>
</code></pre>
<p></p>
<p>Pager Adapter:</p>
<pre><code>public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
MapsFragment tab1 = new MapsFragment();
return tab1;
case 1:
RestaurantsFragment tab2 = new RestaurantsFragment();
return tab2;
case 2:
MyRestaurantsFragment tab3 = new MyRestaurantsFragment();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
</code></pre>
<p>Stack trace:</p>
<pre><code>10-09 12:30:12.755 32374-32374/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.kemo.restaurant, PID: 32374
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.kemo.restaurant/com.test.kemo.restaurant.MainActivity}: java.lang.IllegalStateException: HorizontalScrollView can host only one direct child
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: HorizontalScrollView can host only one direct child
at android.widget.HorizontalScrollView.addView(HorizontalScrollView.java:216)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5347)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| <p>you are adding your fragment to your sliding tab view. you wrote :</p>
<pre><code>fragmentTransaction.replace(R.id.sliding_tabs, restaurantsFragment);
</code></pre>
<p>tab layout is a child of horizontal scrollview see documentation: <a href="https://developer.android.com/reference/android/support/design/widget/TabLayout.html" rel="nofollow">https://developer.android.com/reference/android/support/design/widget/TabLayout.html</a></p>
<p>i dont know how your application works but you cant add your fragment to TabLayout here cause it makes multiple children for that that is now allowed (TabLaout is actually a horizontal scrollView inside)</p>
<p>in <code>fragmentTransaction.replace()</code> method that i mentioned you must specify the container in which you want to add the fragment. from what your code says you are using the tabLayput for title of your viewpager not for replacing your fragment in it.</p>
<p>make a place (container) in your main activity in which you want to add your fragment in. absolutely its not in your <code>R.id.sliding_tabs,</code> beside your titles of viewpager.</p>
|
OR condition in css for screen width and parent div width, . Media query based on parent element width <p>How to write media query based on screen width and parent element width .</p>
<p>currently i create a <code>php</code> plugin which generate some <code>html</code> output . That <code>html</code> out put is responsive ,for that i write some media query . But when i am using this plugin in another web page or website this is not fully responsive , because of parent <code>div</code> element's <code>width</code> in that webpage .
i know how to get parent element <code>width</code> using <strong>javascript</strong> :</p>
<p><code>var width= $(".mydiv").parent().width();</code></p>
<p>(1) My question is, it is possible to write or condition in <code>css</code> so that it will check either the screen width is less than <strong>450</strong>(test value) or the parent <code>div</code> width is less than <strong>450</strong> then apply certain <code>css</code> </p>
<p>(2) Is it possible to use <code>css</code> only for that rule .</p>
<p>please see the code .</p>
<pre><code>.row::after {
content: "";
clear: both;
display: block;
}
@media only screen and (min-width: 725px) {
/* For mobiles: */
.col-m-1 {width: 8.33%;}
.col-m-2 {width: 16.66%;}
.col-m-3 {width: 25%;}
.col-m-4 {width: 33.33%;}
.col-m-5 {width: 41.66%;}
.col-m-6 {width: 50%;}
.col-m-7 {width: 58.33%;}
.col-m-8 {width: 66.66%;}
.col-m-9 {width: 75%;}
.col-m-10 {width: 83.33%;}
.col-m-11 {width: 91.66%;}
.col-m-12 {width: 100%;}
}
@media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
<div class="row">
<div class="col-3 col-m-3 cub-menu">html sidebar elements</div>
<div class="col-9 col-m-9">html main elements </div>
</div>
</code></pre>
<p>currently this is work based on screen width . But when my plugin run on websites then this row div become under other div for example</p>
<pre><code><div class='parrent-clas-something'>
<div class="col-3 col-m-3 cub-menu">html sidebar elements</div>
<div class="col-9 col-m-9">html main elements </div>
</div>
</code></pre>
<p>so what i need is the query is like <code>[@media only screen and (min-width: 768px) || parent element width >768]{</code>
......</p>
<p>}
please help . </p>
| <p>You can add css attribues with jQuery too.</p>
<pre><code>if (width<450){
$(".mydiv").css({
height: '450px',
backgroun: '#000',
position: 'absolute'
})
}
// or ...
$(".mydiv").parent().css ....
</code></pre>
|
Problems with swedish letters MySQL and LAMP <p>I have struggled with this some time. I could not get it to work.</p>
<p>On the url <a href="http://course.easec.se/problem.pdf" rel="nofollow">http://course.easec.se/problem.pdf</a> I have put together what I have done so far!</p>
<p>Any suggestions?</p>
<pre><code><?php
header('Content-Type: text/html; charset=ISO-8859-1'); //no changes
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "db_test4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset("utf8");
echo "From PHP Script ååååå\n"; //to see if there is problem when edit the script
$sql = "SELECT * FROM test_tbl";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Kundid: " . $row["kund_id"]. " - Förnamn: " . $row["fnamn"]. " - Efternamn: " . $row["enamn"]. " - Adress:" . $row["adress1"] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</code></pre>
<p>Client:</p>
<p><img src="http://i.stack.imgur.com/yWVlk.png" alt="Client"></p>
<p><img src="http://i.stack.imgur.com/t6qlD.png" alt=""></p>
<p><img src="http://i.stack.imgur.com/5tEni.png" alt=""></p>
<p>It works now, seems do be my editor, when I tried ANSI instead of UTF-8 and Changes the header to !</p>
<p><a href="https://i.stack.imgur.com/MVBXj.png" rel="nofollow">enter image description here</a></p>
| <p>Directly below</p>
<p><code>$conn = new mysqli($servername, $username, $password, $dbname);</code></p>
<p>add</p>
<p><code>$conn->set_charset("utf8");</code></p>
<p>Note: In addition you should also make sure that the charset of your HTML (in the <code><head></code> tag) is set to <code>utf-8</code>, like <code><meta charset="utf-8"></code></p>
|
Software Architecture: OpenGL Shader creation and compilation <p>I'm about to refactor some parts of a rendering engine, and wonder if a shader should really know it's OpenGL context. Currently, each shader has a bind() and compileShader() method - which do nothing else but call the OpenGL context for the actual task. </p>
<p>It seems common to have these methods implemented in the shader - but is it really good practice? Shouldn't it be better to have the context create, compile and bind a shader? And does a shader necessarily have to know it's context? </p>
<p>Some code snippets below. Here you see that the shader just calls context methods, and therefore compilation could be a concern of the context and not the shader itself. </p>
<pre><code>ShaderPtr hdm::shader::fancy_lines_3d_ptr;
fancy_lines_3d_ptr->compileShader( vert_src.c_str(), frag_src.c_str(), vlayout );
void Shader::bind()
{
assert(_shaderObj);
_context.bindShader(_shaderObj);
}
void Shader::compileShader(const string &vertexSrc,
const string &fragmentSrc,
hdm::rendering::VERTEX_LAYOUT vlayout)
{
_context.compileShader(_shaderObj, vertexSrc.c_str(), vertexSrc.length(), SHADER_TYPE::ST_VERTEX);
_context.compileShader(_shaderObj, fragmentSrc.c_str(), fragmentSrc.length(), SHADER_TYPE::ST_FRAGMENT);
_context.bindAttributeLocations(vlayout, _shaderObj);
_context.linkShader(_shaderObj);
}
</code></pre>
| <p>When it comes to OpenGL and OOP programming no clear cut answers can be given. Due to the way the OpenGL API mixes global state, certain object types confined to a single context and other object types shareable among multiple contexts it's very difficult, if not impossible to perfectly map OpenGL into a OOP model.</p>
<blockquote>
<p>Shouldn't it be better to have the context create, compile and bind a shader?</p>
</blockquote>
<p>Yes! In fact it makes a lot of sense for a OpenGL context to be a <em>factory</em> for OpenGL objects.</p>
<blockquote>
<p>And does a shader necessarily have to know it's context?</p>
</blockquote>
<p>In fact every OpenGL object should know the contexts it's related to. I recommend to implement this via a dedicated abstract context reference class; from that class derive a <em>single context reference</em> that's instanciated by objects that are not shareable (shaders, programs, framebuffer objects, VAOs, â¦) and a <em>shared context reference</em> that's instanciated by objects that <em>are</em> shareable (images, textures, buffer objects, â¦).</p>
<p>And then you somehow should implement a way to track context sharing setup and map this into the shared context reference.</p>
|
Java construrctor with string params <p>How can I extract attributes values from the string parameter ?</p>
<pre><code>public class Pays{
public Pays(String paysDescriptions) {
//implementation
}
}
pays= new Pays("p1:Europe:France, p2:Amerique:Canada");
</code></pre>
<p><strong>Edit:</strong></p>
<p>I gave an answer below to people who have never used this type of constructor (like me :p ) and who may need some explanations.</p>
| <p>You should try using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)" rel="nofollow">String.split(String regex)</a> API.</p>
<ol>
<li>Break the parameter <code>paysDescriptions</code> using comma(<code>,</code>) as <code>regex</code>, then</li>
<li>Break the individual items using colon(<code>:</code>) as <code>regex</code></li>
</ol>
<p><strong>Example:</strong></p>
<pre><code>public Pays(String paysDescriptions) {
String[] split_1 = paysDescriptions.split(",");
for (String split : split_1) {
String[] split_2 = split.split(":");
for (String sp : split_2) {
System.out.println(sp); // use sp.trim() if spaces after comma
// not required.
}
}
}
</code></pre>
|
Why won the if statement execute? <p>I wrote a simple program in Java which writes a word backwards. Trying to check if "hello" works. In <code>if</code>-statement I'm checking that string is equal to "olleh". Could anyone see why the if statement won't execute.</p>
<pre><code>public class MyProgram {
public static void main(String[] args) {
String x = "hello";
System.out.println(back(x));
}
public static String back(String str) {
String y = " ";
String temp = " ";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
}
</code></pre>
| <p>If you will initialize <code>y</code> variable to empty string instead of space your if-statement will execute and print "nice". Also you do not need a <code>temp</code> string as you don't use it. You probably want to return you reverted string back (alternatively you can make your method void and remove the return statement).</p>
<pre><code>public static String back(String str) {
String y = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
</code></pre>
<p>By the way, it's better to use <code>StringBuilder</code> when you're concatenating strings in a loop.</p>
|
Vulnerabity Libpng library <p>I'm using this library for scanning and cropping images but after publishing my apk in the google console developer I get this alert and the apk is rejected :</p>
<blockquote>
<p>Libpng library The vulnerabilities were fixed in libpng v1.0.66,
v.1.2.56, v.1.4.19, v1.5.26 or higher. You can find more information
about how resolve the issue in this Google Help Center article.</p>
</blockquote>
<p>I tried updating openCV to 3.1 but still get the same message.</p>
<p>Probably the problem comes from these because they're pre-compiled with an older version of OpenCV</p>
<blockquote>
<p>\app\src\main\libs\armeabi-v7a\libopencv_java.so</p>
<p>\app\src\main\libs\armeabi-v7a\libScanner.so</p>
</blockquote>
<p>If there's a way to re-compile these files and get the new .so I think it is the solution for that problem.</p>
<p>IDE : Android Studio</p>
<p>LIBRARY : <a href="https://github.com/jhansireddy/AndroidScannerDemo" rel="nofollow">https://github.com/jhansireddy/AndroidScannerDemo</a></p>
| <p>try this sollution i found it on OpenCV site:</p>
<p><a href="http://answers.opencv.org/question/98805/need-update-opencv-manager-apk-for-google-play-warning/" rel="nofollow">http://answers.opencv.org/question/98805/need-update-opencv-manager-apk-for-google-play-warning/</a></p>
|
loading log4j.properties for log4j2 <p>please check the attached image of project structure, let me know if i positioned log4j2.properties right.
also have a look at versions of jars I am using.
I wrote a simple program to print logs on console. in order to achieve this I wrote log4j2.properties file as follows.</p>
<h1>Root logger option</h1>
<p>log4j.rootLogger=INFO, file</p>
<p>log4j.appender.file= org.apache.logging.log4j.core.appender.ConsoleAppender</p>
<p>log4j.appender.file.Target=System.out</p>
<p>log4j.appender.file.Layout=org.apache.logging.log4j.core.layout.PatternLayout</p>
<p>log4j.appender.file.Layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n</p>
<p>Main program is as follows.(also shown in image)</p>
<pre><code>package goldensource.track.logs;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.PropertiesUtil;
public class TestLogger {
private Logger logger;
private PropertiesUtil pu;
TestLogger()
{
System.setProperty("log4j.configurationFile","log4j2.properties");
logger = LogManager.getLogger(TestLogger.class);
logger.info("Yes I am there!");
logger.debug("I am debugging!");
logger.warn("giving you a warner!");
}
public static void main(String[] args) {
TestLogger z = new TestLogger();
}}
</code></pre>
<p>I have created a reference of PropertiesUtil but anyways I am not using it.</p>
<p>when I am executing this program nothing is shown on console. as I could make out, I am not able to load properties file properly.</p>
<p>suggest me any modifications or alternatives with examples.</p>
<p>Thanks in advance! </p>
<p><a href="http://i.stack.imgur.com/rtUzx.png" rel="nofollow"><img src="http://i.stack.imgur.com/rtUzx.png" alt="project Structure"></a></p>
| <p>Without any feedback on the error you are getting, I can guess that one of the problems is with the file name. You should specify the absolute path to your log4j2.properties file when you are setting the system property:</p>
<pre><code>System.setProperty("log4j.configurationFile","/absolute/path/to/log4j2.properties");
</code></pre>
<p>In this way the logger system will know exactly where to find your file.</p>
|
Read characters with scanf("%c, &ch); <p>I must enter characters with white spaces between them. For example, + / 8 7 - 9 '\n' (when I press Enter)
Then I write them in an array of characters and in it have something like this: +/89-9.</p>
<p>How can I skip these white spaces?</p>
<p>I tried to write something, but it doesn't work:</p>
<pre><code>char *arr = new char[1000];
char ch;
scanf("%c", &ch);
int i = 0;
arr[0] = ch;
cout << arr[0];
while (ch != '\n')
{
//scanf("%c", &ch);
scanf("%*[ ]%c", &ch);
cout << (arr[i++] = ch);
}
arr[i++] = '\n';
</code></pre>
| <p>You were fairly close</p>
<pre><code>scanf(" %c", &ch);
</code></pre>
<p>From the <a href="http://en.cppreference.com/w/cpp/io/c/fscanf" rel="nofollow">docs</a>:</p>
<blockquote>
<p>whitespace characters: any single whitespace character in the format
string consumes all available consecutive whitespace characters from
the input (determined as if by calling isspace in a loop). Note that
there is no difference between <code>"\n"</code>, <code>" "</code>, <code>"\t\t"</code>, or other whitespace
in the format string.</p>
</blockquote>
<p>if you want to skip whitespace characters other than <code>\n</code> and keep reading one-by one (needs <code>#include <cctype></code>):</p>
<pre><code>while (ch != '\n') {
scanf("%c", &ch);
if(!isspace(ch)) {
cout << (arr[i++] = ch);
}
}
</code></pre>
|
Can't figure out why my switch isn't working. Seems to not be recognizing the cin input <p>I'm confused as to why my switch won't work, even though I have it set to an integer value. I'm going to be adding more to the program later; just right now trying to initiate options from the menu using a switch.</p>
<p>My switch format looks correct and other examples I've looked at have a very similar look. Though it might be because <code>num</code> could be seen as a string, but I have it set to an integer and have only tried inputting a <code>1</code> to initiate case <code>1</code>. <code>num</code> could be entered in as any positive integer and have three cases for the numbers <code>1</code>, <code>2</code>, and <code>3</code>, each having their their own outputs and a default for any numbers other than those three.</p>
<p>Could someone please help me understand why the switch isn't working?</p>
<pre><code>#include <iostream>
using namespace std;
const double PI = 3.14159;
int main ()
{
int num;
double a,b,c;
double radius, width, length, base, height;
cout << "Shape menu" << endl; // gives user a menu and 3 options
cout << "1. Circle" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Triangle" << endl;
cout << "Choose a shape (1, 2, or 3)" << endl;
cin >> num; // don't get why the switch isn't reading this value
/* ignore this its for later i just wanted to have the formula written down
a = PI * pow(radius,2);
b = width * length;
c = (base * height) / 2;
*/
switch (num){
case1:
cout << "What is the radius?" << endl;
break;
case2:
cout << "Enter width" << endl;
cout << "Enter length" << endl;
break;
case3:
cout << "Enter base" << endl;
cout << "Enter height" << endl;
break;
}
return 0;
}
// compiles fine just doesn't run correctly
</code></pre>
| <p>A space is required between the word <code>case</code> and the actual value for each of the cases. So <code>case1</code> should actually be <code>case 1</code>. So for your code, this:</p>
<pre><code> case1:
/*...*/
case2:
/*...*/
case3:
/*...*/
</code></pre>
<p>Should be changed to this:</p>
<pre><code> case 1:
/*...*/
case 2:
/*...*/
case 3:
/*...*/
</code></pre>
|
Unique index or primary key violation while trying to map Map<Integer,String> in hibernate <p>i am using H2 embedded db and Hibernate 5. I am trying trying to map a HashMap in hibernate this way:</p>
<pre><code>@Entity
public class TestMapping
{
@Id
@GeneratedValue
private Long id;
@ElementCollection
private Map<Integer,String> map = new HashMap<>();
}
</code></pre>
<p>Then i persist TestMapping object contains few pair key-value. When i am trying to see the result in Intellij by executing something like this:</p>
<p><code>SELECT t.* FROM PUBLIC.TESTMAPPING t LIMIT 501</code></p>
<p>i am getting this error:</p>
<p>[<code>23505][23505] Unique index or primary key violation: "PRIMARY KEY ON """".PAGE_INDEX"; SQL statement: ALTER TABLE PUBLIC.TESTMAPPING_MAP ADD CONSTRAINT PUBLIC.FK8CYRSMJWNRD21DCB8T901RHA0 FOREIGN KEY(TESTMAPPING_ID) REFERENCES PUBLIC.TESTMAPPING(ID) NOCHECK [23505-176]</code></p>
<p>I tryied to add <code>@MapKeyColumn</code> nothing work.</p>
<p>mydb.trace.db contains:</p>
<p><code>10-09 13:38:28 database: ALTER TABLE PUBLIC.TESTMAPPING_IMAGES ADD CONSTRAINT PUBLIC.FK9V996C496B8GCB45MJI7WDA0D FOREIGN KEY(TESTMAPPING_ID) REFERENCES PUBLIC.TESTMAPPING(ID) NOCHECK
org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON """".PAGE_INDEX"; SQL statement:
ALTER TABLE PUBLIC.TESTMAPPING_IMAGES ADD CONSTRAINT PUBLIC.FK9V996C496B8GCB45MJI7WDA0D FOREIGN KEY(TESTMAPPING_ID) REFERENCES PUBLIC.TESTMAPPING(ID) NOCHECK [23505-176]
10-09 13:38:29 database: ALTER TABLE PUBLIC.TESTMAPPING_IMAGES ADD CONSTRAINT PUBLIC.FK9V996C496B8GCB45MJI7WDA0D FOREIGN KEY(TESTMAPPING_ID) REFERENCES PUBLIC.TESTMAPPING(ID) NOCHECK
org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON """".PAGE_INDEX"; SQL statement:
ALTER TABLE PUBLIC.TESTMAPPING_IMAGES ADD CONSTRAINT PUBLIC.FK9V996C496B8GCB45MJI7WDA0D FOREIGN KEY(TESTMAPPING_ID) REFERENCES PUBLIC.TESTMAPPING(ID) NOCHECK [23505-176]</code></p>
| <p>This seems to be a problem H2. This man had similar problem:
<a href="http://h2-database.narkive.com/nDbNwitd/h2-unique-index-or-primary-key-violation-primary-key-on-page-index-error" rel="nofollow">http://h2-database.narkive.com/nDbNwitd/h2-unique-index-or-primary-key-violation-primary-key-on-page-index-error</a></p>
|
Accessing localserver through Android <p>I have this code:</p>
<pre><code> @Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
InetAddress ip;
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
String ipv4add;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
ip = InetAddress.getLocalHost();
ipv4add = ip.getHostAddress().toString();
System.out.println(ipv4add);
mWebview .loadUrl(ipv4add+"/Lab4/Task1/index.php");
mWebview.getSettings().setLoadsImagesAutomatically(true);
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
setContentView(mWebview );
} catch (UnknownHostException e) {
e.printStackTrace();
}
</code></pre>
<p>So what it does exactly is first: it should get the server ip that the phone is supposed to be connected to, then after that it will be inserted into the URL so that the phone can connect to the localserver and access my php files. However, when I launch this into my android phone it just crashes. Why does it do so? Hoping you guys can help me solve this. </p>
| <p>You don't have to dynamically request for your server's IP. Or do you? What you can do is get the static IP address of your server (by checking your server's IP configuration) and change to this</p>
<p><code>mWebview .loadUrl("http://your.ip.address.here/Lab4/Task1/index.php");</code></p>
<p>and remove your</p>
<pre><code>ip = InetAddress.getLocalHost();
ipv4add = ip.getHostAddress().toString();
</code></pre>
<p>Once you are ready to deploy to live, the <code>192.168.1.x</code> will have to be replaced with your live domain such as</p>
<p><code>mWebview .loadUrl("http://www.yourdomain.com/Lab4/Task1/index.php");</code></p>
<p>Also, don't forget this in your manifest:</p>
<p><code><uses-permission android:name="android.permission.INTERNET" /></code></p>
|
gulp sass relative paths <p>sass gives an error message</p>
<pre><code>Error: File to import not found or unreadable: helpers/mixins.scss
Parent style sheet: .../temp/styles/all.scss
on line 1 of temp/styles/all.scss
>> @import 'helpers/mixins.scss';
^
</code></pre>
<p>at this point, the code looks like</p>
<pre><code>@import 'helpers/mixins.scss';
@import 'helpers/variables.scss';
@import 'helpers/fonts.scss';
@import '../../node_modules/bootstrap/scss/bootstrap';
@import '../../node_modules/fotorama/fotorama.css';
.navbar {
@extend navbar-light;
@extend bg-faded;
}
</code></pre>
<p>gulp task looks like this</p>
<pre><code>var blocks = 'app/blocks/**/*.scss';
gulp.task('styles', () => (
gulp.src(['app/styles/app.scss', blocks])
.pipe(concat('all.scss'))
.pipe(sass({
errLogToConsole: true,
indentedSyntax: false
}))
.pipe(gulp.dest('temp/styles'))
));
</code></pre>
<p>How to solve this problem?
how to make galp correctly understand the way?</p>
| <p>In your gulp file you can declare sass paths, eg.</p>
<pre><code>var sassPaths = [
'node_modules/bootstrap/scss',
'node_modules/fotorama'
];
</code></pre>
<p>These are relative to your gulp file. </p>
<p>Then set include paths inside your list of sass arguments</p>
<pre><code>.pipe(sass({
errLogToConsole: true,
indentedSyntax: false,
includePaths: sassPaths
}))
</code></pre>
<p>Then in your sass make sure your imports are either relaitve to the parent sass file or relative to one of the include paths.</p>
|
how to convert DateTime format [2016-10-05 11:58:04] using DateTime::createFromFormat <p>i am trying to display a stored DateTime with this format [2016-10-05 11:58:04]. What i want to do is, display the stored date into this readable format [Wed, Oct 10, 2016].</p>
| <p>you can use the method <code>format</code> to choose what to display :</p>
<pre><code><?php
$d = DateTime::createFromFormat("Y-m-d H:i:s", "2016-10-05 11:58:04");
var_dump($d->format("c"));
</code></pre>
<p>look the help here : <a href="http://php.net/datetime.format" rel="nofollow">http://php.net/datetime.format</a></p>
|
MySQL fetch_assoc() shows 1 less result <p>i have a table like below:</p>
<pre><code>hub dep
A B
A C
B D
B E
B F
E G
</code></pre>
<p>i use mysql select to get query and my code is like below:</p>
<pre><code>$sql = "SELECT dep FROM handd WHERE hub='B'";
$result = $conn->query( $sql );
$row = $result->fetch_assoc();
while($row = $result->fetch_assoc()) {
echo "id: " . $row["dep"]."<br>";
}
</code></pre>
<p>but it just gives me result like below:</p>
<pre><code>id: E
id: F
</code></pre>
<p>and i am wondering where is D?</p>
| <pre><code> $row = $result->fetch_assoc();
</code></pre>
<p>This line stores the result of 'B D'. It actually should be:</p>
<pre><code> $sql = "SELECT dep FROM handd WHERE hub='B'";
$result = $conn->query( $sql );
while($row = $result->fetch_assoc()) {
echo "id: " . $row["dep"]."<br>";
}
</code></pre>
|
Some "train" columns aren't present in "test" <p>everyone.</p>
<p>I have a problem. I have to realize a kNN classification on R using LOO. I've found packages "knncat" and "loo" for this. And I've written the code(without LOO):</p>
<pre><code>library(knncat)
x <- c(1, 2, 3, 4)
y <- c(5, 6, 7, 8)
train <- data.frame(x, y)
x1 <- c(9, 10, 11, 12)
y1 <- c(13, 14, 15, 16)
test <- data.frame(x1, y1)
answer <- knncat(train, test, classcol = 2)
</code></pre>
<p>And I've got an error "Some "train" columns aren't present in "test"". I don't understand, what am I doing wrong? How can I fix this error?</p>
<p>If something's wrong with my English, sorry, I'm from Russia:) </p>
| <p>Well, there are some problems with your approach and <code>knncat</code>:</p>
<ol>
<li>You have to specify class labels for the <code>train</code> and <code>test</code> data sets and set <code>classcol</code> accordingly. </li>
<li>Only class labels which appear in train must be present in test. </li>
<li>The columns names of train and test must be the same, or knncat will throw the error you've mentioned: <code>"Some "train" columns aren't present in "test"</code>.</li>
<li>Moreover if you are using integer values as class labels, they have to start from <strong>zero</strong> or knncat will throw an error: <code>"Number in class 0 is 0! Abort!"</code>.</li>
</ol>
<p>Here is an working example:</p>
<pre><code>train <- data.frame(x1=1:4, x2=5:8, y=c(0, 0, 1, 1))
test <- data.frame(x1=9:12, x2=13:16, y=c(1, 0, 0, 1))
knncat(train, test, classcol = 3)
</code></pre>
<p>With the result:</p>
<pre><code>Test set misclass rate: 50%
</code></pre>
|
How to use MetaTrader4.Manager.Wrapper to create an account and change password? <p>How to use MT4 ManageAPI to create an account and change password?
Can you show me a demo?</p>
<p>Thank you very much!</p>
| <p>UserRecordNew method should be used to create new user and UserPasswordSet to update password:</p>
<pre><code> using (var mt = new ClrWrapper (new ConnectionParameters { Login = 123456, Password = "managerPassword", Server = "serverIp:serverPort" }))
{
var user = new UserRecord
{
Group = "demoforex",
Leverage = 100,
Name = "Test account",
Password = "qwe123",
PasswordInvestor = "qwe123"
};
var result = mt.UserRecordNew(user);
var passwordChangeResult = mt.UserPasswordSet(user.Login, "newPass123", 0/*0 - to change trader's password, 1 - investor*/, 0/*0 - not to clean public key, 1 - to clean public key*/)
}
</code></pre>
<p><code>result</code> equals 0 means that user was successfully created. Newly create user login will be usigned to <code>user.Login</code> property.</p>
<p>All parameters in above example are mandatory. Passwords must be between 6 and 15 character and must contain at least contain at least one lowercase letter and one number</p>
|
How to calculate sum with two variables? <p>I'm trying to express a fuction with two variables, e.g:</p>
<p><img src="http://i.stack.imgur.com/hUIdJ.jpg" alt="Fuction"></p>
<p>where <code>S(i,j)</code> is a matrix, <code>j=1:100</code>, <code>i=1:50</code>.</p>
<p>The denominator part is easy</p>
<pre><code>for j=1:100
M(j,1) = sum(S(j,:));
end
</code></pre>
<p>My problem is: I got confused when trying to contain <code>i</code> in the loop and get <code>M(i)</code>.</p>
| <p>First of all, in matlab you dont need the loop to get the sum for the denominator.</p>
<p><code>sum()</code> can get the dimension along which you wish to sum over as the second input argument.
second, in order to get the other expression you simply need to creat a temporary matrix for the multiplication in your matrix and then multiply elementwise.
lets call it J</p>
<pre><code>J = repmat(1:50,[100 1]);
M = sum(J.*S,2)./sum(S,2);
</code></pre>
<p>of course you can sace the memory and simply not save J to memory:</p>
<pre><code>M = sum(repmat(1:50,[100 1]).*S,2)./sum(S,2);
</code></pre>
|
Laravel 5 Eloquent ORM select where - array as parameter <p>I'm getting grade_id from the database:</p>
<p><code>$grade_id = DB::table('grades')->where('teacher_id',$teacher_id)->select('grade_id')->get();</code></p>
<p>and then I want to use that grade_id array in the where eloquent clause so I run</p>
<pre><code>$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', $grade_id)
->get();
</code></pre>
<p>but when I run this I'm getting an error: <code>Object of class stdClass could not be converted to string</code></p>
<p>What could be the problem? Thanks guys.</p>
| <p>Depending on laravels version your <code>$grade_id</code> is either an array or a collection of objects. What you need is an array or a collection of values.
You can achieve that using the <code>pluck()</code> method insted of <code>select()</code> like IzzEps suggested.</p>
<p>But you can get the same result by passing a subquery to the <code>whereIn()</code> method:</p>
<pre><code>$gradeSubquery = DB::table('grades')->where('teacher_id',$teacher_id)->select('grade_id');
$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', $gradeSubquery)
->get();
</code></pre>
<p>This way you will run only one query instead of two.</p>
<p><strong>Update:</strong> Before version 5.2 you have to use <code>lists()</code> instead of <code>pluck()</code>. And the <code>whereIn()</code> method doesn't accept a <code>Builder</code> as second parameter. To get the same query you would need to use a closure:</p>
<pre><code>$home_feed = Home::join('home_grade', 'home_grade.home_id', '=', 'homes.id')
->whereIn('grade_id', function($query) use($teacher_id) {
$query->from('grades')
->where('teacher_id', $teacher_id)
->select('grade_id');
})
->get();
</code></pre>
|
Maximum recursion depth exceeded in python <p>I am trying to make power function by recursion.
But I got run time error like Maximum recursion depth exceeded.
I will appreciate any help!!
Here is my code.</p>
<pre><code> def fast_power(a,n):
if(n==0):
return 1
else:
if(n%2==0):
return fast_power(fast_power(a,n/2),2)
else:
return fast_power(fast_power(a,n/2),2)*a
</code></pre>
| <p>You should use <code>n // 2</code> instead of <code>n / 2</code>:</p>
<pre><code>>>> 5 // 2
2
>>> 5 / 2
2.5
</code></pre>
<p>(At least in python3)</p>
<p>The problem is that once you end up with floats it takes quite a while before you end up at <code>0</code> by dividing by <code>2</code>:</p>
<pre><code>>>> from itertools import count
>>> n = 5
>>> for i in count():
... n /= 2
... if n == 0:
... break
...
>>> i
1076
</code></pre>
<p>So as you can see you would need more than 1000 recursive calls to reach <code>0</code> from <code>5</code>, and that's above the default recursion limit. Besides: that algorithm is meant to be run with integer numbers.</p>
<hr>
<p>This said I'd write that function as something like:</p>
<pre><code>def fast_power(a, n):
if n == 0:
return 1
tmp = fast_power(a, n//2)
tmp *= tmp
return a*tmp if n%2 else tmp
</code></pre>
<p>Which produces:</p>
<pre><code>>>> fast_power(2, 7)
128
>>> fast_power(3, 7)
2187
>>> fast_power(13, 793)
22755080661651301134628922146701289018723006552429644877562239367125245900453849234455323305726135714456994505688015462580473825073733493280791059868764599730367896428134533515091867511617127882942739592792838327544860344501784014930389049910558877662640122357152582905314163703803827192606896583114428235695115603966134132126414026659477774724471137498587452807465366378927445362356200526278861707511302663034996964296170951925219431414726359869227380059895627848341129113432175217372073248096983111394024987891966713095153672274972773169033889294808595643958156933979639791684384157282173718024930353085371267915606772545626201802945545406048262062221518066352534122215300640672237064641040065334712571485001684857748001990405649808379706945473443683240715198330842716984731885709953720968428395490414067791229792734370523603401019458798402338043728152982948501103056283713360751853
</code></pre>
|
AggregateByKey fails to compile when it is in an abstract class <p>I'm new to both Scala and Spark, so I'm hoping someone can explain why aggregateByKey fails to compile when it is in an abstract class. This is about the simplest example I can come up with:</p>
<pre><code>import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD
abstract class AbstractKeyCounter[K] {
def keyValPairs(): RDD[(K, String)]
def processData(): RDD[(K, Int)] = {
keyValPairs().aggregateByKey(0)(
(count, key) => count + 1,
(count1, count2) => count1 + count2
)
}
}
class StringKeyCounter extends AbstractKeyCounter[String] {
override def keyValPairs(): RDD[(String, String)] = {
val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("counter"))
val data = sc.parallelize(Array("foo=A", "foo=A", "foo=A", "foo=B", "bar=C", "bar=D", "bar=D"))
data.map(_.split("=")).map(v => (v(0), v(1)))
}
}
</code></pre>
<p>Which gives:</p>
<pre><code>Error:(11, 19) value aggregateByKey is not a member of org.apache.spark.rdd.RDD[(K, String)]
keyValPairs().aggregateByKey(0)(
^
</code></pre>
<p>If I instead use a single concrete class, it compiles and runs successfully:</p>
<pre><code>import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD
class StringKeyCounter {
def processData(): RDD[(String, Int)] = {
val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("counter"))
val data = sc.parallelize(Array("foo=A", "foo=A", "foo=A", "foo=B", "bar=C", "bar=D", "bar=D"))
val keyValPairs = data.map(_.split("=")).map(v => (v(0), v(1)))
keyValPairs.aggregateByKey(0)(
(count, key) => count + 1,
(count1, count2) => count1 + count2
)
}
}
</code></pre>
<p>What am I missing?</p>
| <p>If you change:</p>
<pre><code>abstract class AbstractKeyCounter[K] {
</code></pre>
<p>To:</p>
<pre><code>abstract class AbstractKeyCounter[K : ClassTag] {
</code></pre>
<p>This will compile.</p>
<p><strong>Why</strong>? <code>aggregateByKey</code> is a method of <code>PairRDDFunctions</code> (your <code>RDD</code> is implicitly converted into that class), which has the following signature:</p>
<pre><code>class PairRDDFunctions[K, V](self: RDD[(K, V)])
(implicit kt: ClassTag[K], vt: ClassTag[V], ord: Ordering[K] = null)
</code></pre>
<p>This means its constructor expects <em>implicit</em> values of types <code>ClassTag[K]</code> and <code>vt: ClassTag[V]</code>. Your abstract class has no knowledge of what K is, and therefore cannot provide a matching implicit value. This means the implicit conversion into <code>PairRDDFunctions</code> "fails" (compiler doesn't perform the conversion) and therefore the method <code>aggregateByKey</code> can't be found.</p>
<p>Adding <code>[K : ClassTag]</code> is shorthand for adding an implicit argument <code>implicit kt: ClassTag[K]</code> to the abstract class constructor, which is then used by compiler and passed to the constructor of <code>PairRDDFunctions</code>.</p>
<p>For more about ClassTags and what they're good for see <a href="https://medium.com/@sinisalouc/overcoming-type-erasure-in-scala-8f2422070d20#.7g4tof8ke" rel="nofollow">this good article</a>. </p>
|
understanding file input output <p>hi i have some problem understanding my lecture material and thought maybe someone here can help me understand it a bit better </p>
<p>this is the example i have in lecture</p>
<pre><code>private void readFileExample (String inFilename){
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try {
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
lineNum = 0;
line = bufRdr.readLine();
while (line != null) {
lineNum++;
processLine(line);
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e) {
if (fileStrm != null) {
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
</code></pre>
<p>also i have a slide on parsing csv files</p>
<pre><code>private void processLine(String csvRow) {
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ",");
while (strTok.hasMoreTokens()) {
thisToken = strTok.nextToken();
System.out.print(thisToken + " ");
}
System.out.println("");
}
</code></pre>
<p>i guess the processLine method is used in readFileExample to seperate the csv file is that right?</p>
<p>and also if my understanding is correct, im supposed to input a file name somewhere and call that into readFileExample but how would i do that, can i use </p>
<pre><code>Scanner sc = new scanner (system.in)
filename = sc.nextline()
</code></pre>
<p>and if its not too much a simple example would be great</p>
<p>thanks for the help.</p>
| <p>It doesn't matter how you input file name. </p>
<p>It can go like this: <strong>String fileName = new String("myFileName");</strong></p>
<p>or the way you have: </p>
<p><strong>Scanner sc = new scanner (system.in);</strong></p>
<p><strong>filename = sc.nextline();</strong></p>
<p>Then after you set the fileName, pass it to readFileExample:</p>
<p><strong>readFileExample(filename);// Whatever you get the name from, pass it.</strong></p>
<p>And processLine function, just like it's name, which is for parse each line. If you want to use this program to implement some sort of file analysis. Just use your structure above. but you have to modify the processLine function.</p>
|
I want to catch the exception when I assign a varchar string to numeric variable <p><strong>My code is as below</strong>:</p>
<pre><code>set serveroutput on;
declare
a number(3);
alta exception;
pragma exception_init (alta, -06550);
begin
a:=&numberl;
dbms_output.put_line(a);
exception
when alta then
dbms_output.put_line('this is your exception');
end;
</code></pre>
| <p>I guess you want to catch ORA-06502</p>
<pre><code>declare
a number(3);
alta exception;
pragma exception_init (alta, -06502);
begin
a:=&numberl;
dbms_output.put_line(a);
exception
when alta then
dbms_output.put_line('this is your exception');
end;
</code></pre>
|
how to repopulate a form in codeigniter <p>I am trying to repopulate a codeigniter form, when I click the submit button the form input disappears. I have tried to use the set value function but its not working, I am auto loading the form helper. </p>
<p>form view </p>
<pre><code> <?php $attributes= array('id'=>'registration_form','class'=>'registration_form');?>
<div class="row">
<div class="large-4 large-offset-8 columns">
<?php if($this->session->flashdata('reg_errors')):?>
<?php echo $this->session->flashdata('reg_errors');?>
<?php endif;?>
</div>
</div>
<?php echo form_open('User/registration_check',$attributes);?>
<div class="registration_form">
<div class="row">
<div class="large-2 large-offset-8 columns">
<?php
$data = array(
'class'=>'form-control',
'id'=>'fname',
'name'=>'fname',
'placeholder'=>'First Name',
'value'=> set_value('fname')
);
echo form_input($data);
?>
</div>
<div class="large-2 columns">
<?php
$data = array(
'class'=>'form-control',
'name'=>'lname',
'placeholder'=>'Last Name'
);
echo form_input($data);
?>
</div>
</div>
</div>
<div class="row">
<div class="large-4 large-offset-8 columns">
<?php
$data = array(
'class'=>'form-control',
'name'=>'email',
'placeholder'=>'Email'
);
echo form_input($data);
?>
</div>
</div>
<div class="row">
<div class="large-4 large-offset-8 columns">
<?php
$data = array(
'class'=>'form-control',
'name'=>'cemail',
'placeholder'=>'Confirm Email'
);
echo form_input($data);
?>
</div>
</div>
<div class="row">
<div class="large-4 large-offset-8 columns">
<?php
$data = array(
'class'=>'form-control',
'name'=>'password',
'placeholder'=>'Password'
);
echo form_input($data);
?>
</div>
</div>
<div class="row">
<div class="large-4 large-offset-8 columns">
<?php
$data = array(
'class'=>'form-control',
'name'=>'cpassword',
'placeholder'=>'Confirm Password'
);
echo form_input($data);
?>
</div>
<div class="large-1 large-offset-8 columns">
<?php echo "<select name='day' id='day'><option value='default'>day</option>";
for($i=1; $i<32; $i++){
echo "<option value='$i'".($i==$_POST["day"] ? " selected" : null).">$i</option>";
}
echo "</select>";?>
</div>
<div class="medium-1 columns">
<?php
echo "<select name='month' id='month'><option value='default'>month</option>";
for($i=1; $i<13; $i++){
echo "<option value='$i'".($i==$_POST["month"] ? " selected" : null).">$i</option>";
}
echo "</select>";
?>
</div>
<div class="medium-2 columns">
<?php
echo "<select name='year'id='year'><option value='default' >year</option>";
for($i=1900; $i<2016; $i++){
echo "<option value='$i'".($i==$_POST["year"] ? " selected" : null).">$i</option>";
}
echo "</select>";
?>
</div>
<div class="row">
<div class="large-3 large-offset-9 columns">
<div class="row">
<div class="large-2 large-offset-2 columns">
<?php
$data = array(
'class'=>' success button',
'name'=>'register',
'id'=>'register',
'value'=>'Register'
);?>
<?php echo form_submit($data);?>
</div>
</div>
</div>
</div>
<?php echo form_close();?>
</code></pre>
<p>user controller </p>
<pre><code>class User extends CI_Controller {
public function index()
{
$this->load->view('templates/head');
$this->load->view('templates/home_header');
$this->load->view('webPages/home');
$this->load->view('templates/footer');
}
public function registration_check() {
$this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[users.user_email]');
$this->form_validation->set_rules('cemail','Confirm Email','trim|required|matches[email]');
$this->form_validation->set_rules('fname','Firstname','trim|required|min_length[5]');
$this->form_validation->set_rules('lname','Lastname','trim|required|min_length[5]');
$this->form_validation->set_rules('password','Password','trim|required|min_length[5]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|min_length[5]|matches[password]');
$this->form_validation->set_message('is_unique','email already in use');
if($this->form_validation->run()) {
//generates a random key
$key = md5(uniqid());
$this->load->library('email',array('mailtype'=>'html'));
$this->load->model('User_model');
$this->email->from('c3392262@joshpercival.co.uk',"joshua percival");
$this->email->to($this->input->post('email'));
$this->email->subject("Account Confirmation");
$message = "<p>Thank you for signing up</p>";
$message .= "<p><a href ='".base_url()."index.php/Users/register_user/$key'>Click here</a> to confirm your account</p>";
$this->email->message($message);
if( $this->User_model->add_temp($key)) {
if($this->email->send()){
$data['title'] = 'Confirmation Email Sent';
$email['email'] = $this->input->post('email');
$this->load->view('templates/header',$data);
$this->load->view('authentication/email_sent_success',$email);
} else {
echo 'email was not sent';
}
} else {
echo 'could not add to database';
}
//add to temp database
} else {
$data = array(
'reg_errors'=> validation_errors()
);
$this->session->set_flashdata($data);
redirect('User/index');
}
}
</code></pre>
| <p>The problem is in this block of code</p>
<pre><code>}
else
{
$data = array('reg_errors'=> validation_errors());
$this->session->set_flashdata($data);
redirect('User/index');
}
</code></pre>
<p>You cannot use redirect with form_validation in this way and retain the instance of <code>form_validation</code> you have been using. </p>
<p>With the redirect the server discards your current instance of CI (and all loaded classes - including form_validation) and then will create a whole new instance of CI. The <code>set_value()</code> function uses information gathered by <code>form_validation->run()</code> but that is long gone. It has no information to use to repopulate the forms. </p>
<p>Take another very close look at the <a href="http://www.codeigniter.com/user_guide/libraries/form_validation.html#form-validation-tutorial" rel="nofollow">Form Validation Tutorial</a> and notice there is no <code>redirect</code> call involved.</p>
|
making a text document a numeric list <p>I am trying to automatically make a big corpus into a numeric list. One number per line. For example I have the following data:</p>
<pre><code>Df.txt =
In the years thereafter, most of the Oil fields and platforms were named after pagan âgodsâ.
We love you Mr. Brown.
Chad has been awesome with the kids and holding down the fort while I work later than usual! The kids have been busy together playing Skylander on the XBox together, after Kyan cashed in his $$$ from his piggy bank. He wanted that game so bad and used his gift card from his birthday he has been saving and the money to get it (he never taps into that thing either, that is how we know he wanted it so bad). We made him count all of his money to make sure that he had enough! It was very cute to watch his reaction when he realized he did! He also does a very good job of letting Lola feel like she is playing too, by letting her switch out the characters! She loves it almost as much as him.
so anyways, i am going to share some home decor inspiration that i have been storing in my folder on the puter. i have all these amazing images stored away ready to come to life when we get our home.
With graduation season right around the corner, Nancy has whipped up a fun set to help you out with not only your graduation cards and gifts, but any occasion that brings on a change in one's life. I stamped the images in Memento Tuxedo Black and cut them out with circle Nestabilities. I embossed the kraft and red cardstock with TE's new Stars Impressions Plate, which is double sided and gives you 2 fantastic patterns. You can see how to use the Impressions Plates in this tutorial Taylor created. Just one pass through your die cut machine using the Embossing Pad Kit is all you need to do - super easy!
If you have an alternative argument, let's hear it! :)
</code></pre>
<p>First I read the text using the command <code>readLines</code>:</p>
<pre><code>text <- readLines("Df.txt", encoding = "UTF-8")
</code></pre>
<p>Secondly I get all the text into lower letters and I remove unnecessary spacing:</p>
<pre><code>## Lower cases input:
lower_text <- tolower(text)
## removing leading and trailing spaces:
Spaces_remove <- str_trim(lower_text)
</code></pre>
<p>From here on, I will like to assign each line a number e.g.:</p>
<pre><code>"In the years thereafter, most of the Oil fields and platforms were named after pagan âgodsâ." = 1
"We love you Mr. Brown." = 2
...
"If you have an alternative argument, let's hear it! :)" = 6
</code></pre>
<p>Any ideas?</p>
| <p>You already do kinda have numeric line # associations with the vector (it's indexed numerically), butâ¦</p>
<pre><code>text_input <- 'In the years thereafter, most of the Oil fields and platforms were named after pagan âgodsâ.
We love you Mr. Brown.
Chad has been awesome with the kids and holding down the fort while I work later than usual! The kids have been busy together playing Skylander on the XBox together, after Kyan cashed in his $$$ from his piggy bank. He wanted that game so bad and used his gift card from his birthday he has been saving and the money to get it (he never taps into that thing either, that is how we know he wanted it so bad). We made him count all of his money to make sure that he had enough! It was very cute to watch his reaction when he realized he did! He also does a very good job of letting Lola feel like she is playing too, by letting her switch out the characters! She loves it almost as much as him.
so anyways, i am going to share some home decor inspiration that i have been storing in my folder on the puter. i have all these amazing images stored away ready to come to life when we get our home.
With graduation season right around the corner, Nancy has whipped up a fun set to help you out with not only your graduation cards and gifts, but any occasion that brings on a change in one\'s life. I stamped the images in Memento Tuxedo Black and cut them out with circle Nestabilities. I embossed the kraft and red cardstock with TE\'s new Stars Impressions Plate, which is double sided and gives you 2 fantastic patterns. You can see how to use the Impressions Plates in this tutorial Taylor created. Just one pass through your die cut machine using the Embossing Pad Kit is all you need to do - super easy!
If you have an alternative argument, let\'s hear it! :)'
library(dplyr)
library(purrr)
library(stringi)
textConnection(text_input) %>%
readLines(encoding="UTF-8") %>%
stri_trans_tolower() %>%
stri_trim() -> corpus
# data frame with explicit line # column
df <- data_frame(line_number=1:length(corpus), text=corpus)
# list with an explicit line number field
lst <- map(1:length(corpus), ~list(line_number=., text=corpus[.]))
# implicit list numeric ids
as.list(corpus)
# explicit list numeric id's (but they're really string keys)
setNames(as.list(corpus), 1:length(corpus))
# named vector
set_names(corpus, 1:length(corpus))
</code></pre>
<p>There are a <em>plethora</em> of R packages that significantly ease the burden of text processing/NLP ops. Doing this work outside of them is likely to be reinventing the wheel. The <a href="https://cran.r-project.org/web/views/NaturalLanguageProcessing.html" rel="nofollow">CRAN NLP Task View</a> lists many of them.</p>
|
How to stop div collapsing over other html content <p>I've been trying to code a website to have the main section fill 100% of the screen on all devices (i.e. the logo, navbar, slider and quote fill the whole screen, then you scroll down and the next section is 'Contact Me'). On my laptop screen and iPhone 6 it looks correct, but on smaller mobile screens (and when I resize my browser to a small size) the 'Contact Me' section seems to collapse over the other content. </p>
<p>I've tried setting a minimum width on the div (as that's what many of the suggestions seem to be) but with no luck. </p>
<p>I've attached a link to the website, any suggestions would be much appreciated.</p>
<p><a href="http://176.32.230.9/andycheckcheck.co.uk/homepage.html" rel="nofollow">http://176.32.230.9/andycheckcheck.co.uk/homepage.html</a></p>
| <p>You have this CSS rule in there:</p>
<pre><code>.firstSection {
height: 100%;
width: 100%;
background-color: #EDF4ED;
}
</code></pre>
<p>Change <code>height</code> to <code>min-height</code> in there and add <code>height: 100%</code> to <code>body</code>:</p>
<pre><code>.firstSection {
min-height: 100%;
width: 100%;
background-color: #EDF4ED;
}
body {
height: 100%;
}
</code></pre>
|
How to get list of all music in specific directory and all subdirectories using MediaStore <p>What I need is to get result like from this code</p>
<pre><code>ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
</code></pre>
<p>but in a specific directory, not from all directories.
This is what I've tried so far:</p>
<pre><code>ContentResolver musicResolver = mContext.getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = null;
try {
musicCursor = musicResolver.query(uri,
new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
},
MediaStore.Audio.Media.DATA + "=? ",
new String[]{new File("some path to directory").getCanonicalPath()},
null);
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
<p>But this method <code>moveToFirst()</code>
returns false so as I understood it's empty.
Thanks for your future help.</p>
| <pre><code> searchpath = "%" + yourpath + "%";// looking for path string
ContentResolver musicResolver = mContext.getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = null;
try {
musicCursor = musicResolver.query(uri,
new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
},
MediaStore.Audio.Media.DATA + "LIKE? ",
new String[]{searchpath},
null);
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
|
How to add SharePoint Online PowerShell to Visual Studio Code and Cmder <p>I installed <strong>SharePoint Online PowerShell</strong> to interact with Office 365 sites, I would like SharePoint Online PowerShell to be added as an option to <strong>Visual Studio Code</strong> terminal and also how to add it to <strong>Cmder</strong>?</p>
| <p>For <a href="https://code.visualstudio.com/" rel="nofollow">Studio Code</a> install <a href="https://github.com/PowerShell/PowerShell/blob/master/docs/learning-powershell/using-vscode.md" rel="nofollow"><code>PowerShell Extension</code></a> which provides PowerShell language support for Visual Studio Code.</p>
<p>Once <a href="https://www.microsoft.com/en-us/download/details.aspx?id=42038" rel="nofollow">SharePoint Online Client Components SDK</a> is installed, you can write and debug SharePoint PowerShell scripts using Visual Studio Code. </p>
<p><strong>Results</strong></p>
<p>PS script debugging</p>
<p><a href="http://i.stack.imgur.com/av5xC.png" rel="nofollow"><img src="http://i.stack.imgur.com/av5xC.png" alt="enter image description here"></a></p>
|
UWP support for opengl <p>guys.
I have a opengl library written in c++. I know that I can use Angle but because of this I will need to code in C++ my whole app. Is there a way to use c++ opengl in UWP and still use C# as a main language?</p>
| <blockquote>
<p>Is there a way to use c++ opengl in UWP and still use C# as a main language?</p>
</blockquote>
<p>ANGLE is currently the only way to get the OpenGL API to run in UWP. More details please reference <a href="https://social.msdn.microsoft.com/Forums/en-US/ae97534f-8f48-4bf9-ae7e-2c7a12e75190/uwp-opengl-in-c?forum=wpdevelop" rel="nofollow">this thread</a>.</p>
<p>You can write your own via interop if you want to use ANGLE from c#. You can just write your low level OpenGL stuff in C++ and wrapper it, and invoke it by c# in your logic level. </p>
<p>Fortunately, people who has same requirements with you created an issue on the GitHub few days ago, and got samples from @mattleibow. @mattleibow shared his code in <a href="http://stackoverflow.com/questions/39432377/marshalling-eglrenderresolutionscaleproperty-to-angle-from-c-sharp-using-p-inv">this thread</a>. More details please reference <a href="https://github.com/Microsoft/angle/issues/89" rel="nofollow">OpenGL surface from SwapChainPanel declared in XAML in C#</a>.</p>
<p>Additionally, <a href="https://github.com/Microsoft/angle" rel="nofollow">ANGLE</a> is actually for translating OpenGL ES to DirectX. So I recommend you to use <a href="https://github.com/Microsoft/Win2D" rel="nofollow">Win2D</a> instead. Win2D is a new, immediate mode 2D drawing framework for XAML applications on Windows 8.1 and Windows 10. It is built on the high performance foundation of DirectX, but is designed to provide the convenience and ease of use expected by C# and .NET developers. More details you can reference <a href="https://channel9.msdn.com/events/build/2015/2-631" rel="nofollow">this video</a>.</p>
|
CSS width property for image <p>I want a 1200x300 resolution image on my webpage with width equal to the screen size and a height of 500px. My code doesn't seem to work. This is my CSS: </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-css lang-css prettyprint-override"><code> div.fix
{ /*min-width:100%;*/
/*width:100%;*/
width:2000px;
height:500px;
position:fixed;
display:block;
top: 0px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "fix" ><img src="ARIA.png">
</div> <!-- I have tried inline styling as well. But it doesnt work --></code></pre>
</div>
</div>
</p>
<p>I don't think this might be the reason, but is it because my image size is smaller than the specified size? </p>
<p>Thanks:)</p>
| <p><strong>Try this:</strong></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-css lang-css prettyprint-override"><code>.fix img{
width:100%;
height:500px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "fix" >
<img src="http://placehold.it/1200x300">
</div></code></pre>
</div>
</div>
</p>
|
Really simple Java code not working <p>I am an absolute beginner to programming and I've started with java. I wrote this code and I just don't know what's wrong with it.</p>
<pre><code>public class multiples3and5 {
public static void main(String[] args) {
for (int mult3 = 0; mult3 < 1000; mult3 += 3);
System.out.println(mult3);
}
}
</code></pre>
<p>I keep getting this error on my terminal:</p>
<pre><code>multiples3and5.java:7: error: cannot find symbol
System.out.println(mult3);
^
symbol: variable mult3
location: class multiples3and5
1 error
</code></pre>
| <p>You didn't start your code block properly. At the end of the <code>for</code> loop declaration, you put a semicolon instead of an opening curly bracket <code>{</code>. Without code, this just looped through and removed the <code>mult3</code> variable from the scope, because it was declared for the loop.</p>
<p>This is the fix:</p>
<pre><code>public class multiples3and5 {
public static void main(String[] args){
for(int mult3 = 0; mult3 < 1000; mult3 += 3){
System.out.println(mult3);
}
}
}
</code></pre>
|
Bean Annotation to override XML definition - Spring <p>My spring-boot application has another library project included as a dependency. This library project has a spring.xml file where a number of beans defined. One of these beans has another external dependency injected which I don't need in my project. Hence this is throwing an error when I start my application. I want to define the same bean in my application as a java config and make spring-boot ignore the specific bean from spring.xml file. However I want all the other beans in spring.xml to be read.</p>
| <p>Define a bean in your local java config with the same name and type as the one inherited in the spring.xml file. </p>
<p>Annotate your bean with <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html" rel="nofollow">@Primary</a> which will make yours used over the imported one.</p>
<p>Your application will still use the definitions of all the other beans you inherit. </p>
<p>To prevent other defined beans loading that you do not actually need you have to change the bean creation to <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html" rel="nofollow">lazy</a> configuration, that is, they only get created when explicitly used. </p>
<p>To do this in your main Spring boot class where the application is created, most likely annotated with <code>@SpringBootApplication/ @Configuration/ @EnableAutoConfiguration/ @ComponentScan</code> you should add <code>@Lazy</code> above it.</p>
<p>Usually you would explicitly annotate the Bean in question but here it cannot be done as it is originating in a spring.xml file in a 3rd party jar. The idea here is to cleanly state all beans are lazy from the highest point in the spring configuration.</p>
|
TypeError: Cannot read property 'plugins' of undefined for cordovaLocalNotification plugin <p>I am developing hybrid application by using ionic platform. I am implementing cordovalocalnotification features but it prompt out with cannot read property 'plugins' of undefined. The following is my code. Anyone can help me to solve this problem.</p>
<p>index.html</p>
<p>
</p>
<pre><code><head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter" ng-controller="SampleController">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Local Notification Sample</h1>
</ion-header-bar>
<ion-content>
<button class="button button-block button-positive" ng-click="scheduleInstantNotification()">
Instant
</button>
</ion-content>
</ion-pane>
</body>
</html>
</code></pre>
<p>app.js</p>
<pre><code>angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
$rootScope.$on('$cordovaLocalNotification:schedule',
function (event, notification, state) {
console.log("SCHEDULE");
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:trigger',
function (event, notification, state) {
console.log("TRIGGER");
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:update',
function (event, notification, state) {
console.log('UPDATE');
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:cancel',
function (event, notification, state) {
console.log('CANCEL');
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
});
})
.controller('SampleController',
function ($scope, $cordovaLocalNotification, $ionicPlatform) {
$ionicPlatform.ready(function () {
$scope.scheduleInstantNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
text: 'Instant Notification',
title: 'Instant'
}).then(function () {
alert("Instant Notification set");
});;
};
};
});
});
</code></pre>
| <p>Use <code>window.cordova.plugins</code> instead of <code>cordova.plugins</code></p>
<pre><code>if (window.cordova && window.cordova.plugins.Keyboard) {
//cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
</code></pre>
|
How to extract strings from a file in PHP <p>I have a txt file.</p>
<p>source.txt:</p>
<pre><code>test.com,Test
www.cnn.com,CNN
twitter.com,Twitter
</code></pre>
<p>I want to print it like</p>
<p>Output:</p>
<pre><code><a target="_blank" href="http://test.com">Test</a>
<a target="_blank" href="http://www.cnn.com">CNN</a>
<a target="_blank" href="http://twitter.com">Twitter</a>
</code></pre>
<p>My code doesn't work:</p>
<pre><code>$array = explode("\n", file_get_contents('/home/source.txt'));
echo '<a target="_blank" href="http://' . $array[0] . '">'. $array[1] . '</a>'
</code></pre>
| <pre><code>// explode file by end off line
$array = explode("\n", file_get_contents('/home/source.txt'));
// here $array[0] should be "test.com,Test"
// lets loop
foreach($array as $item) {
// now create array from our line of text
$data = explode(",", $item);
// output
echo '<a target="_blank" href="http://' . $data[0] . '">'. $data[1] . '</a>';
}
</code></pre>
<p>Better?</p>
|
How to compare each value returned by web_reg_save_param function with another parameter in Load Runner <p>I am working on Load Runner 12.53. I have one web_reg_save_param function with ORDINAL as below:
web_reg_save_param("paramname","LB=","RB=","ORDINAL=ALL",LAST);
It will return some vales lets say my parameter name is ID and I will get values like ID_1, ID_2,...etc Now I have one more parameter (Say X).</p>
<p>Can you please tell me how can I compare X with ID's. Like
<code>if(ID_3 == X) {
//Some code
}</code></p>
<p>I have to print the ID value which is equals to parameter X.</p>
<p>Here ID_Count is not fixed. </p>
| <p>see C function <strong>strcmp()</strong> and loadrunner function <strong>lr_eval_string()</strong></p>
|
Page name as a php variable <p>I am working on a project that requires me to redirect the user to a php page. And the name of the page to be redirected to is stored as a php variable.This is what I tried. Suppose <code>$var</code> is the name of the php file. I want to do something like this,</p>
<pre><code>if(condition)
{
header("Location: '$var'.php");
}
</code></pre>
<p>How do I do this?</p>
| <p>You simply need to follow string concatenation here. Try this:</p>
<pre><code>if (condition) {
header("Location: ".$var.".php");
}
</code></pre>
<p>Refer to <a href="http://php.net/manual/en/language.operators.string.php" rel="nofollow">String Operators</a></p>
|
why does the debug mode not work well when using R-Devel? <p>I am trying to test the new R-Devel using Rstudio and I see there are some issues with the debugging mode like:</p>
<ul>
<li>green arrow is missing</li>
<li>Traceback is dim</li>
</ul>
<p>is there a reason for this?</p>
| <p>There are some known issues with RStudio and the latest versions of R-devel, due to a change in the memory layout of some internal C structures in R used by RStudio for the debugger.</p>
<p>Unfortunately, the changes required to accommodate this have not yet landed in RStudio.</p>
|
Windows batch script to rename files that have random names? <p>I need to make windows batch script to rename files that have random names. I have a folder with thousand .txt files, their names are completely random,
I want to rename first 5 files in that folder to <code>file1.txt, file2.txt,file3.txt, file4.txt,file5.txt</code>.</p>
<p>Help appreciated.</p>
| <p>Is this okay?</p>
<pre><code>@ECHO OFF
(SET f=C:\Test)
IF /I "%CD%" NEQ "%f%" PUSHD "%f%" 2>NUL||EXIT/B
SET "i=5"
FOR %%A IN (*.txt) DO CALL :SUB "%%A"
EXIT/B
:SUB
IF %i% GTR 0 REN %1 File%i%.txt
SET/A i-=1
</code></pre>
<p>Just change line two if your stated directory path\name has changed.</p>
|
Need help writing an SQL query for a select statement <p>I need help with an SQL query.
I want to show lines from my test_related_orders table where the current user id equals the user_id in my test_related_orders table and where order_unlock_time (from my table) is <= acutal timestamp. Until here all works fine. But now it gets complicated.
I also need to check/restrict in my wp_posts table if there is an post_author equals to my test_related_orders user_id who has an existing order_number same as from my test_related_orders order_number.</p>
<p>If this statement is true the associated lines from my test_related_orders will be shown. If this statement is false there should be no associated lines.</p>
<p>(So when I delete an order in the woocommerce frontend the statement should'nt return a string for this entry.)</p>
<p>Here is my existing code:</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>$user_id = get_current_user_id();
//Timestamp for current system time
date_default_timezone_set("Europe/Berlin");
$timestamp = date("Y-m-d H:i:s");
//Database Query
$abfrage = "SELECT * FROM test_related_orders WHERE user_id = '$user_id' AND order_unlock_time <= '$timestamp'";
</code></pre>
</div>
</div>
</p>
<p>I think I can use an INNER JOIN and I've tried it here:</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>INNER JOIN wp_posts ON '$user_id' = post_author WHERE....</code></pre>
</div>
</div>
</p>
<p>but it's to complicated for me as a beginner.</p>
<p>Here are my database structures:</p>
<p>The test_related_orders structure:
The order_number looks like: DE-1016-835 and the user_id as a normal number/id like 1 in this example.</p>
<p><a href="http://i.stack.imgur.com/2QgTA.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/2QgTA.jpg" alt=""></a></p>
<p>The wp_posts database structure: </p>
<p><a href="http://i.stack.imgur.com/9Mtqu.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/9Mtqu.jpg" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/9skvG.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/9skvG.jpg" alt="enter image description here"></a></p>
<p>The last picture is an example entry from the wp_posts. The problem is that I have to grab the order number from post_title and for this I have to remove the first word "Lieferschein" from this title to get the order_number and there's no extra field for the number...</p>
<p>Thank you for your help! I hope I explained it completely.</p>
| <p>First problem to solve is getting the order number from the post_title so that you can compare the values in your inner join. A primitive way of doing this, assuming the order number is always in form AA-DDDD-DDD would be</p>
<pre><code>SELECT right(post_title, 11) as posts_order_number
</code></pre>
<p>As you've already discovered, an inner join is what you need, as it'll only return results where the tables match. Note you usually join tables based on their columns, rather than directly comparing to your '$user_id' string (and you've already filtered for this in your where clause).</p>
<p>You can join on more than one field at a time, to match on order number as well as user_id.</p>
<p>Your query now becomes:</p>
<pre><code>SELECT *
FROM test_related_orders tro
INNER JOIN wp_posts p
ON tro.user_id = p.post_author
AND tro.order_number = right(p.post_title, 11)
WHERE tro.user_id = '$user_id' AND order_unlock_time <= '$timestamp'
</code></pre>
|
How to set a single color to values bigger than 0 but smaller than 1? <p>I have a matrix of nxn, for example: </p>
<pre><code>[ 0 1 1 ;
0.2 1 0.1;
0 0.4 0]
</code></pre>
<p>I want to visualize my matrix and I want:</p>
<ul>
<li>All values = 1 to be black</li>
<li>All values between 0 and 1 (0 < value <1) to be white </li>
<li>All values = 0 to be a specific color (red for example). </li>
</ul>
<p>As in the following image:</p>
<p><a href="http://i.stack.imgur.com/RL5Yi.png" rel="nofollow"><img src="http://i.stack.imgur.com/RL5Yi.png" alt="Example"></a></p>
<p>How can I achieve this?</p>
| <p>The following solution builds color map, and use <code>ind2rgb</code> to create RGB image: </p>
<ul>
<li>Convert A to "indexed image" (expand by 256, and round) - indexed image elements must be integers. </li>
<li>Create color map meeting range conditions.</li>
<li>Use <code>ind2rgb</code> for converting X to RGB image with created color map.</li>
</ul>
<p>Check the following code sample:</p>
<pre><code>A = [ 0 1 1;...
0.2 1 0.1;...
0 0.4 0];
%N - Number of elements in the color map (e.g 256) applies "quantization level".
N = 256;
%Convert A to "indexed image" in range [0, N].
X = round(A*N);
%Create color map with N elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%R, G, B (Red, Green, Blue) applies three color components of color map.
R = zeros(N, 1);
G = zeros(N, 1);
B = zeros(N, 1);
%Create array of 100 values in range 0 to 1
V = linspace(0, 1, N);
%All values = 1 to be black
R(V == 1) = 0;
G(V == 1) = 0;
B(V == 1) = 0;
%All values between 0 and 1 (0 < value <1) to be white
R((V > 0) & (V < 1)) = 1;
G((V > 0) & (V < 1)) = 1;
B((V > 0) & (V < 1)) = 1;
%All values = 0 to be a specific color (red for example).
R(V == 0) = 1;
G(V == 0) = 0;
B(V == 0) = 0;
%Concatenate color components, and form Nx3 color map.
cmap = [R, G, B];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Convert A to RGB, using colormap cmap.
RGB = ind2rgb(X, cmap);
imshow(RGB);
</code></pre>
<p>The solution is not the most simple solution, but it can be used for solving more general visualization problems.</p>
<p>Result (enlarged):<br>
<a href="https://i.stack.imgur.com/b3vPA.png" rel="nofollow"><img src="https://i.stack.imgur.com/b3vPA.png" alt="enter image description here"></a></p>
|
How to group set of time under distinct date from csv file <p>hi i have just gotten a set of time and date data from csv file using regex:</p>
<pre><code>datePattern = re.compile(r"(\d+/\d+/\d+\s+\d+:\d+)")
for i, line in enumerate(open('sample_data.csv')):
for match in re.finditer(datePattern, line):
date.append(match.groups());
</code></pre>
<p>the output is [('30/06/2016 08:30',), ('20/07/2016 09:30',),
('30/06/2016 07:30',)</p>
<p>How do i turn it into useful information such as listing all the time under the same date such as maybe [('30/06/2016 08:30',07.30),]</p>
| <p>Try this regex:</p>
<pre><code>r"(\d+/\d+/\d+)\s+(\d+:\d+)"
</code></pre>
<p><a href="https://repl.it/DrqS/2" rel="nofollow">Python code</a> follows, I have used dictionary of lists for such grouping</p>
<pre><code>import re
datePattern = re.compile(r"(\d+/\d+/\d+)\s+(\d+:\d+)")
dateDict =dict()
for i, line in enumerate(open('sample_data.csv')):
for match in re.finditer(datePattern,line):
if match.group(1) in dateDict:
dateDict[match.group(1)].append(match.group(2))
else:
dateDict[match.group(1)] = [match.group(2),]
print(dateDict)
</code></pre>
<p>It will output as follows:</p>
<pre><code>{'10/10/1990': ['12:20', '11:20'], '10/10/1991': ['16:20', '16:20']}
Tested with python 3+
</code></pre>
|
Restrict Access To Certain File From Other Programs And Users While Running <p>I am in process of building an app which writes data continuously to a file. When I start the program the file is created and starts being written to. <br>
However I noticed that <strong>sometimes</strong> if I have Windows Explorer open, access to the file is denied to my app, and an error is thrown. <br></p>
<pre><code>fs = new System.IO.FileStream(location,
System.IO.FileMode.Open,
System.IO.FileAccess.Write,
System.IO.FileShare.ReadWrite);
</code></pre>
<p>So how do I restrict access to this file so only my app can access it, not any other programs? </p>
| <p>You can change the last parameter from <code>System.IO.FileShare.ReadWrite</code> to <code>System.IO.FileShare.None</code>.</p>
<p>That locks the file in <code>location</code> exclusively as long as this stream is open and no other app can read, modify or delete that file except your own <code>FileStream</code>.</p>
<p>In fact this isn't only true for other apps - even your own app can't open another <code>FileStream</code> of that file. So keep it open as long as you need but don't forget to correctly dispose the <code>FileStream</code> after use.</p>
|
Sql Exception in count query with joins <p>I have a problem with following code</p>
<pre><code>public long findDataCount(EntityUiBean entityUIBean){
long count = 0;
StringBuffer sql = new StringBuffer();
sql.append("select count(a.id) from")
.append(" entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join "
+ "city_master c on c.id=b.city_id ")
.append(" with b.entity_id=a.id ");
if (!entityUIBean.getMasterCompanyId().equals("0") || entityUIBean.getMasterCompanyId().equals("")) {
sql.append("and d.other_entity_id=" + entityUIBean.getMasterCompanyId());
}
boolean b = true;
if (entityUIBean.isDateStatus()) {
if (b)
sql.append(" and ");
sql.append(" a.inserted_date between '").append(entityUIBean.getYearF()).append("-")
.append(entityUIBean.getMonthF() + 1).append("-").append(entityUIBean.getDayF()).append("' and '")
.append(entityUIBean.getYearT()).append("-").append(entityUIBean.getMonthT() + 1).append("-")
.append(entityUIBean.getDayT()).append(" 23:59:59'");
}
if (entityUIBean.getLocation() != null && !entityUIBean.getLocation().equals("")) {
if (b)
sql.append(" and ");
sql.append("c.cityname like '%").append(entityUIBean.getLocation().trim()).append("%'");
b = true;
}
if (entityUIBean.getEntityIdComma() != null && !entityUIBean.getEntityIdComma().equals("")) {
if (b)
sql.append(" and ");
sql.append("a.id in(").append(entityUIBean.getEntityIdComma().trim()).append(")");
b = true;
}
if (entityUIBean.getName() != null && !entityUIBean.getName().equals("")) {
if (b)
sql.append(" and ");
sql.append("a.entity_name like '%").append(entityUIBean.getName().trim()).append("%'");
b = true;
}
if (entityUIBean.getMobile() != null && !entityUIBean.getMobile().equals("")) {
if (b)
sql.append(" and ");
sql.append("(b.mobile_number1 like '%").append(entityUIBean.getMobile().trim())
.append("%' or b.mobile_number2 like '%").append(entityUIBean.getMobile()).append("%')");
b = true;
}
if (entityUIBean.getEmail() != null && !entityUIBean.getEmail().equals("")) {
if (b)
sql.append(" and ");
sql.append("b.email like '%").append(entityUIBean.getEmail().trim()).append("%'");
b = true;
}
if (entityUIBean.getStatus() > -1) {
if (b)
sql.append(" and ");
sql.append("a.entity_status =").append(entityUIBean.getStatus());
b = true;
}
if (entityUIBean.getEntityType() != null && !entityUIBean.getEntityType().equals("")) {
if (b)
sql.append(" and ");
{
if (entityUIBean.getEntityType().equals("corporate") || entityUIBean.getEntityType().equals("vendor"))
sql.append("a.entity_type ='").append(entityUIBean.getEntityType()).append("'");
else
sql.append("a.entity_type !='corporate' and a.entity_type !='vendor'");
}
b = true;
} else
sql.append(" and a.entity_type !='corporate' and a.entity_type !='vendor'");
MY_LOGGER.info("SQL Query is : "+sql.toString());
try {
count =(Long) getHibernateTemplate().find(sql.toString()).get(0);
} catch (Exception re) {
MY_LOGGER.error("SERVICE:AuLoginDao.checkLoginStatus Fail sql=" + sql, re, 1);
throw re;
}
return count;
}
</code></pre>
<p>The stack trace is :</p>
<pre><code> type Exception report
message Request processing failed; nested exception is org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.til.et.sme.listing.web.controller.CustomFilter.doFilter(CustomFilter.java:75)
root cause
org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, column 76 [select count(a.id) from entity_listing a left outer join relation_master d on d.entity_id=a.id, entity_location b left outer join city_master c on c.id=b.city_id with b.entity_id=a.id and a.entity_type !='corporate' and a.entity_type !='vendor']
org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:660)
org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:904)
com.til.et.sme.listing.db.dao.impl.EntityMasterDaoImpl.findDataCount(EntityMasterDaoImpl.java:338)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
com.til.et.sme.listing.core.utils.SimpleProfiler.profile(SimpleProfiler.java:30)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:620)
org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:609)
org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy101.findDataCount(Unknown Source)
com.til.et.sme.listing.db.dao.impl.MasterDaoImpl.getCountForEntityQuery(MasterDaoImpl.java:405)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
com.til.et.sme.listing.core.utils.SimpleProfiler.profile(SimpleProfiler.java:30)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:620)
org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:609)
org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy111.getCountForEntityQuery(Unknown Source)
com.til.et.sme.listing.web.controller.MasterController.entityManage(MasterController.java:340)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:178)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:444)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:432)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.til.et.sme.listing.web.controller.CustomFilter.doFilter(CustomFilter.java:75)
</code></pre>
<p>I don't seem to understand the cause of the problem. The query is executed successfully in MySQL but through code it throws exception. Please help me with the query.</p>
| <p>You have <code>WITH</code> keyword in place of <code>AND</code> (I took the query from your <em>stack trace</em>)</p>
<pre><code>SELECT Count(a.id)
FROM entity_listing a
LEFT OUTER JOIN relation_master d
ON d.entity_id = a.id,
entity_location b
LEFT OUTER JOIN city_master c
ON c.id = b.city_id
WITH --Here
b.entity_id = a.id
AND a.entity_type != 'corporate'
AND a.entity_type != 'vendor'
</code></pre>
<p>Not sure what you are trying to achieve but <code>AND</code> is what expected(should compile now)</p>
<pre><code>SELECT Count(a.id)
FROM entity_listing a
LEFT OUTER JOIN relation_master d
ON d.entity_id = a.id,
entity_location b
LEFT OUTER JOIN city_master c
ON c.id = b.city_id
AND b.entity_id = a.id
AND a.entity_type NOT IN ( 'corporate', 'vendor' )
</code></pre>
<p><strong>Note :</strong> You can use <code>NOT IN</code> operator instead of multiple <code>!=</code> conditions </p>
<p><strong>Update :</strong> </p>
<p>You have combined explicit <code>JOIN</code> syntax and comma separated old style Join syntax may be that could be the problem. Try this</p>
<pre><code>SELECT Count(a.id)
FROM entity_listing a
LEFT OUTER JOIN relation_master d
ON d.entity_id = a.id
JOIN entity_location b
ON b.entity_id = a.id
LEFT OUTER JOIN city_master c
ON c.id = b.city_id
AND a.entity_type NOT IN ( 'corporate', 'vendor' )
</code></pre>
|
Android Updating A TextView From A Different Activity <p>I'm new to android and not 100% certain I have the terminology of my question correct, but here it is.</p>
<p>I have a layout that has a <code>TextView</code> that I want to reflect a setting. The problem I am facing is that the Setting page ("customsignalsetup") is navigated to from the page that the <code>TextView</code> I want to update is situated on. When the option is changed on the settings page, and closed using <code>Finish()</code>, the <code>TextView</code> hasn't updated. However, if I close the page the <code>TextView</code> is on, then open it again, it has updated.</p>
<p>Here's my code:</p>
<p><strong>TextView Update Code (Before any changes on the settings page)</strong></p>
<pre><code>settings = getSharedPreferences("CustomSignalSettings", 0);
TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);
CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");
</code></pre>
<p><strong>Code To Handle "Settings" Pressed From Menu And Switch To Settings Page</strong></p>
<pre><code> public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.custom_signal_setup:
// Open Settings Page
Intent intent = new Intent(PLCActivity.this, customsignalsetup.class);
startActivity(intent);
return true;
case R.id.help:
//get help
return true;
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p><strong>Setting Page Code To Update TextView</strong></p>
<pre><code> public class customsignalsetup extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customplcsettingspopup);
Button button = (Button) findViewById(R.id.save);
button.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.save:
//THE BELOW LINE IS SUPPOSED TO SET 'CustLabel' TO THE TEXTVIEW TO BE UPDATED
TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);
SharedPreferences settings = getSharedPreferences("CustomSignalSettings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("CustomSignalUnit",CusUnit.getText().toString());
editor.commit();
// THE BELOW LINE IS SUPPOSED TO UPDATE THE TEXTVIEW ON A DIFFERENT PAGE
CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");
finish();
}
}
}
</code></pre>
<p>My code throws no errors, but the TextView simply doesn't update. Im assuming this is because the activity loaded the original textview hasn't ended yet and only future labels will be updated?</p>
<p>Thanks</p>
| <p>put this line like this so you will get the updated value everytime. </p>
<pre><code>@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");
}
</code></pre>
|
gwtbootstrap3 with them adminLTE <p>how can I to integrate this theme in may project?
now, i've the simple bootstrap3 but I like to change.</p>
<p>
Yay buttons!</p>
<pre><code> <b:Button>Some button</b:Button>
<b:Button type="DANGER" size="LARGE">Dangerous button</b:Button>
</b:Container>
</code></pre>
| <p>The GWT Bootstrap 3 project has theming instructions in the <a href="https://gwtbootstrap3.github.io/gwtbootstrap3-demo/#setup" rel="nofollow">Setup section</a>.</p>
|
SCCM 2012 Perquisite Check "SQL Server service running Account Error" <p>Getting """SQL Server service running Account Error"</p>
<p>Description as provided
"The logon account for the SQL Server service cannot be a local user account, NT SERVICE\ or LOCAL SERVICE. You must configure the SQL Server service to use a valid domain account, NETWORK SERVICE, or LOCAL SYSTEM."
Tried to resolve by adding a domain user for SQL server and starting service with that account, didn't work.</p>
<p>Check screenshots. </p>
<ol>
<li><p><a href="http://i.stack.imgur.com/O4xVh.png" rel="nofollow">Error Screenshot during prequisite check</a></p></li>
<li><p><a href="http://i.stack.imgur.com/Hl3j9.png" rel="nofollow">I am already running the service as a Domain User</a></p></li>
</ol>
<p>Couldn't manage to pass this check.</p>
<p>OS : Windows Server 2012
SQL Server : SQL Server 2012
SCCM : SCCM 2012</p>
| <p><strong>1. Install using at least SQL server standard version instead</strong></p>
<p>You have installed SQL server Express which is not supported for CAS/Primary site installation. Please use at least SQL server standard instead. For more details about SQL server 2012 requirement, please see below:</p>
<p><a href="http://i.stack.imgur.com/TPhdU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/TPhdU.jpg" alt="enter image description here"></a></p>
<p>Here is the MS best practice for the account running SQL server service in ConfigMgr:</p>
<p>"Running the SQL Server service using the local system account of the SQL Server computer is not a SQL Server best practice. For the most secure operation of SQL Server site database servers, a low rights domain user account should be configured to run the SQL Server service."</p>
<p><strong>2. Create and register SPN</strong></p>
<p>When you configure a domain user as the account running SQL server service. You will also have to register the SPN to allow clients to identify and authenticate the service using Kerberos authentication. The command line registering the SPN:</p>
<p>To create an SPN for the NetBIOS name of the SQL Server use the following command: <strong>setspn âA MSSQLSvc/:1433 </strong></p>
<p>To create an SPN for the FQDN of the SQL Server use the following command: <strong>setspn -A MSSQLSvc/:1433 </strong></p>
|
How to reuse jquery function <p>Hey guys I have a problem with re-using code:</p>
<pre><code>YT_ready(function() {
$("iframe[id]").each(function() {
var identifier = this.id;
var frameID = getFrame(identifier);
if (frameID) { //If the frame exists
players[frameID] = new YT.Player(, {
events: {
'onStateChange': onPlayerStateChange
}
});
}
});
</code></pre>
<p>});</p>
<p>tried this..</p>
<pre><code> slide('code', function() {
YT_ready();
});
</code></pre>
| <p>Try this:</p>
<pre><code>var handler=function(thi) {
$("iframe[id]").each(function() {
var identifier = thi.id;
var frameID = getFrame(identifier);
if (frameID) { //If the frame exists
players[frameID] = new YT.Player(, {
events: {
'onStateChange': onPlayerStateChange
}
});
}
};
YT_ready(function(){handler(this)});
slide('code', function(){handler(this)});
</code></pre>
<p>I had to add some wrapping to get the correct value of <strong>this</strong> into the handler.</p>
|
not getting the right value onclick <p>I have a slider and two buttons for left and right
I have tow event handlers for each button as I'll show you in the code bellow. </p>
<p>when I click and wait for the transition to be completed, everthing works fine,
but when I click fast consecutive clicks ,I'm getting float not exact numbers as expected (as shown in the HTML bellow)</p>
<p><strong><em>this is Javascript and Jquery mixed together :</em></strong></p>
<pre><code>var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");
left.addEventListener("click", function(){
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);
if(parsedMarginLeft > -800) {
$('#container').animate({marginLeft: '-=200px'}, 0);
}
});
right.addEventListener("click", function(){
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);
if(parsedMarginLeft < 0) {
$('#container').animate({marginLeft: '+=200px'}, 0);
}
});
</code></pre>
<p><strong><em>And this is the html I get after the clicks :</em></strong></p>
<pre><code><div id="container" style="width: 1800px; margin-left: -127.879px;">
</div>
</code></pre>
| <p>You may use the <a href="https://api.jquery.com/animated-selector/" rel="nofollow">:animated</a> selector as first line in your event listeners to test if the container div is running animation:</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-js lang-js prettyprint-override"><code>var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");
left.addEventListener("click", function(){
if ($('#container:animated').length == 0) {
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);
if(parsedMarginLeft > -800) {
$('#container').stop().animate({marginLeft: '-=200px'}, 0);
}
}
});
right.addEventListener("click", function(){
if ($('#container:animated').length == 0) {
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);
if (parsedMarginLeft < 0) {
$('#container').animate({marginLeft: '+=200px'}, 0);
}
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="left">left</button>
<button id="right">right</button>
<div id="container" style="width: 1800px; margin-left: 0px;background-color: red;">
aaaaaaaaaaaaaaaaa
</div></code></pre>
</div>
</div>
</p>
|
Firefox link color flickers when using transition with :hover and :visited <p>I'm testing the following code in Firefox 49.0 (under Linux Mint):</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-css lang-css prettyprint-override"><code>a{
font-size:50px;
color:gray;
font-weight:1000;
transition:color 1s;
}
a:hover{
color:black;
}
a:visited{
color:lightgray;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="">VISITED LINK</a><br>
<a href="https://google.com/randomtext">LNK NOT VISITED</a></code></pre>
</div>
</div>
</p>
<p><a href="http://codepen.io/anon/pen/EgEmax" rel="nofollow">Here is a codepen</a> if you like that more. In case the code is not clear: I want the links to be constant lightgray when visited, gray when not visited, and black when hovering a not visited link. Also, I want to transition between these colors.</p>
<p>However, firefox seems to apply the :hover rule first to the visited links when hovered, and then the :visited rule, and also transitioning between these, thus the flickering.</p>
<p>I can't seem to find a workaround this.</p>
<p>Edit: Chrome displays it the way I want.</p>
| <p>This seems to be a Firefox bug, the transitions are not handled correctly.</p>
|
how to add menu items <p>Like the older version of android studio menu is not pre generated. So I tried and added some code of my own. But unfortunately I am unable to add menu items. So need some help:(</p>
<p>MainActivity:</p>
<pre><code>package com.buckydroid.materialapp;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>Menu xml:</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:title="next"
android:orderInCategory="100"
android:icon="@drawable/refresh"
app:showAsAction="always"
/>
</menu>
</code></pre>
<p>app_bar:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"
android:background="@color/colorPrimary"
android:title="@string/app_name"
android:titleTextColor="#fff"
>
</Toolbar>
</code></pre>
<p>So if you need any other codes then comment :(</p>
| <p>Change your code in MainActivity.java</p>
<p>from</p>
<pre><code> @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
</code></pre>
<p>To</p>
<pre><code>@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
</code></pre>
<p>I hope it will fix the problem...</p>
|
Unknown Class X in Interface Builder File <p>I am working with Xcode 7 and swift.</p>
<p>I am trying to connect a label that is on a Collection View prototype cell to my code. I know to do this, I have to make a subclass of UICollectionViewCell and put it in that class instead of the view controller, which I did. I run the app immediately after adding the outlet to the subclass, and the app crashes. I noticed at the top of the error message it says: Unknown Class nameOfSubclass in Interface Builder File. I have looked at other stack overflow questions and they say it is a simple matter of setting the module under the custom class. I did this, but the app still crashes and now it says: Unknown class _TtC13 (app name / module name) 17(nameOfSubclass) in Interface Builder file. </p>
<p><a href="http://i.stack.imgur.com/Yb4yG.png" rel="nofollow">identity inspector of the prototype cell</a></p>
<p><a href="http://i.stack.imgur.com/3gO71.png" rel="nofollow">identity inspector of the UICollectionView</a></p>
<p>Code</p>
<pre><code>import UIKit
class SecondViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
private let reuseIdentifier = "hourlyWeatherCell"
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 48
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) //as! hourlyWeatherCell
// Configure the cell
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
printDate()
// Do any additional setup after loading the view.
self.collectionView.dataSource = self
self.collectionView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class hourlyWeatherCell: UICollectionViewCell {
@IBOutlet weak var temperatureHLabel: UILabel!
}
}
</code></pre>
| <p>With a little tinkering I got it to work. For some reason Xcode was not compiling the subclass it the UIViewContoller. I simply moved the subclass out of the view controller class (making the subclass a class), and everything worked fine. </p>
|
Overfitting after first epoch <p>I am using convolutional neural networks (via Keras) as my model for facial expression recognition (55 subjects). My data set is quite hard and around 450k with 7 classes. I have balanced my training set per subject and per class label.</p>
<p>I implemented a very simple CNN architecture (with real-time data augmentation):</p>
<pre><code>model = Sequential()
model.add(Convolution2D(32, 3, 3, border_mode=borderMode, init=initialization, input_shape=(48, 48, 3)))
model.add(BatchNormalization())
model.add(PReLU())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(256))
model.add(BatchNormalization())
model.add(PReLU())
model.add(Dropout(0.5))
model.add(Dense(nb_output))
model.add(Activation('softmax'))
</code></pre>
<p>After first epoch, my training loss decreases constantly while validation loss increases. Could overfitting happen that soon? Or is there a problem with my data being confusing? Should I also balance my testing set?</p>
| <p>It could be that the task is easy to solve and after one epoch the model has learned enough to solve it, and training for more epochs just increases overfitting.</p>
<p>But if you have balanced the train set and not the test set, what may be happening is that you are training for one task (expression recognition on evenly distributed data) and then you are testing on a slightly different task, because the test set is not balanced.</p>
|
how do i make a standalone C# form application with data storage(without SQL)? <p>i am trying to make an C# form application which will store some data like id, name, date and contact no. i have done it using MS SQL server's local connectivity. the problem is it requires MS SQL Server installed on my other PC or else it is useless.</p>
<p>Is there any other way i can store and edit my data using some sort of local storage option which can let me do it without SQL server, i want to use my application on other PCs without installing SQL server on them.</p>
| <p>as rene suggested You can use local files to store your data. most of the time i use configuration file (*.ini).</p>
<p>please read more about ini files in the below wiki link </p>
<p><a href="https://en.wikipedia.org/wiki/INI_file" rel="nofollow">ini file info</a></p>
<p>hope this helps</p>
|
All Hive functions fail <p>I honestly don't know what is going on. Everything fails except basically <code>SHOW DATABASES</code>. </p>
<p>Nothing on this page (below) even works. Everything gives me a NoViableAltException. This is both in Hive and Beeline CLI. </p>
<p><a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions" rel="nofollow">https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions</a></p>
<p>My opinion is I shouldn't have to be connected to a DB to execute these commands which didn't initially work. But, I decided to try connecting to the default DB and still all the same failures. Created a new DB and same failures. Sources I've used for doc info...</p>
<p><a href="http://www.folkstalk.com/2011/11/date-functions-in-hive.html" rel="nofollow">http://www.folkstalk.com/2011/11/date-functions-in-hive.html</a></p>
<p><a href="http://www.folkstalk.com/2011/11/difference-between-normal-tables-and.html" rel="nofollow">http://www.folkstalk.com/2011/11/difference-between-normal-tables-and.html</a></p>
<p><a href="http://hortonworks.com/wp-content/uploads/2016/05/Hortonworks.CheatSheet.SQLtoHive.pdf" rel="nofollow">http://hortonworks.com/wp-content/uploads/2016/05/Hortonworks.CheatSheet.SQLtoHive.pdf</a></p>
<p><a href="http://stackoverflow.com/questions/30399544/add-minutes-to-datetime-in-hive">Add minutes to datetime in Hive</a></p>
<p>Nothing works. All NoViableAltException exception. I started the cloudera manger and all things check healthy except Impala. I'm using the CDH5 quickstart docker image. Tried both hive and beeline cli. Any help would be appreciated. </p>
<p>EDIT: Here is an example from another StackOverflow question that fails though different exception.</p>
<pre><code>0: jdbc:hive2://localhost:10000/default> from_unixtime(unix_timestamp());
Error: Error while compiling statement: FAILED: ParseException line 1:0 cannot recognize input near 'from_unixtime' '(' 'unix_timestamp' (state=42000,code=40000)
0: jdbc:hive2://localhost:10000/default>
</code></pre>
<p>This one is a different exception but I can't get anything other than show databases/tables/etc to work.</p>
<p>Here is another...</p>
<pre><code>hive> DATEDIFF('2000-03-01', '2000-01-10');
NoViableAltException(26@[])
at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1024)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:423)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:311)
at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1194)
at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1289)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1120)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1108)
at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:218)
at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:170)
at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:381)
at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:773)
at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:691)
at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:626)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
FAILED: ParseException line 1:0 cannot recognize input near 'DATEDIFF' '(' ''2000-03-01''
</code></pre>
<p>Literally nothing I see on the net that should work works. </p>
| <p>Just add SELECT.</p>
<pre><code>SELECT from_unixtime(unix_timestamp());
SELECT DATEDIFF('2000-03-01', '2000-01-10');
</code></pre>
|
Django: How to properly make shopping cart? ( Array string field ) <p>Lately I've been needing to create a server-side shopping cart for my website that can have products inside. I could add cart and product in session cookies, but I prefer to add it to my custom made User model, so it can stay when the user decides to log out and log back in.</p>
<p>Since I'm making a shopping cart, I need to make a model for it, that will hold products as objects, so then they can be easily used, but I can't find any way to do so properly.</p>
<pre><code>class User(models.Model):
username = models.CharField(max_length=150)
joined = models.DateTimeField('registered')
avatar = models.CharField(max_length=300)
balance = models.IntegerField(default=0)
ban = models.BooleanField()
cart = models.???
def __str__(self):
return self.username
</code></pre>
<p>How can I achieve having array string in models with using Django's system? If not then can it be possible by other libraries ( Json, Pickle ), but I've seen it can be done by ForeignKey, if so how is it possible?</p>
| <p>I'd suggest using DB relationships instead of storing a string or an array of strings for this problem.</p>
<p>If you solve the problem using DB relationships, you'll need to use a <a href="https://docs.djangoproject.com/es/1.10/topics/db/examples/many_to_many/" rel="nofollow">ManyToManyField</a>.</p>
<pre><code>class User(models.Model):
...
cart = models.ManyToManyField(Product)
</code></pre>
<p>And assuming you have a model for your products.</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=8, decimal_places=2)
</code></pre>
<p>When adding elements to the cart you'll use something like this.</p>
<pre><code>tv = Product(name='LED TV', ...)
tv.save()
diego = User.objects.get(username='dalleng')
diego.cart.add(some_product)
</code></pre>
|
Why Javascript in-built methods/functions are written in C/C++ and not JS syntax <p>This question is in reference to this old question <a href="http://stackoverflow.com/questions/10289182/where-can-i-find-javascript-native-functions-source-code">Where-can-i-find-javascript-native-functions-source-code</a></p>
<p>The answer on that page says, that the source code is in <code>c</code> or <code>c++</code> but I am curious as to why the source (definition) is in those languages? I mean they are JS functions definitions for e.g <code>toString()</code> method. It's a JavaScript function so its definition must be written using Javascript syntax.</p>
<p><code>toString;</code> in chrome console outputs <code>function toString() { [native code] }</code>. </p>
<p>If it's a user-defined function then you can see the definition but not <code>toString()</code> or for that matter other in-built functions
after all they are just function/methods that must be defined in JavaScript syntax for the engine to interpret them correctly.</p>
<p>I hope you can understand what point I am trying to make.</p>
| <p>As pointed out in the comments, you have a fundamental misunderstanding of how JavaScript works.</p>
<p>JavaScript is a <em>scripting</em> language, in the purest sense of that term, i.e. it is meant to script a <em>host environment</em>. It is meant to be embedded in a larger system (in this case, a web browser written in C/C++) to manipulate that system in a limited way.</p>
<p>Some other examples would be bash as the scripting language of unix, python as the scripting language of the sublime text editor, elisp as the scripting language of emacs, lua as the scripting language for World of Warcraft, etc.</p>
<p>When we say a function is 'built-in', we mean it is actually a function of the hosting environment (e.g. web-browser), not a function of the scripting language (JavaScript).</p>
<p>Although the JavaScript standard mandates certain built in functions, all that means is that a conforming host environment needs to expose that functionality, regardless of what language the underlying implementation is in.</p>
|
Format vs. Concatenate URLs <p>I recently came across tutorial code like this:</p>
<pre><code># Constant strings for OAuth2 flow
# The OAuth authority
authority = 'https://login.microsoftonline.com'
# The token issuing endpoint
token_url = '{0}{1}'.format(authority, '/common/oauth2/v2.0/token')
</code></pre>
<p>Is there a compelling reason to use <code>format</code> instead of string concatenation in this context? I've seen the arguments in favor of <code>format</code> when you've got text separating your data, or where you're inserting values from a dictionary. But in this scenario it seems so much cleaner and more readable to just do something like:</p>
<pre><code>authority = 'https://login.microsoftonline.com'
token_url = authority + '/common/oauth2/v2.0/token'
</code></pre>
| <p>To join url use the appropriate method:</p>
<pre><code>import urllib
authority = 'https://login.microsoftonline.com'
token_url = urllib.basejoin(authority, '/common/oauth2/v2.0/token')
</code></pre>
|
Update Fragment UI from Service or BroadcastReceiver if Fragment is visible <p><strong>TL;DR</strong> </p>
<p>I need to update a fragment's UI(toggleButton) when it is visible on screen from a running Service.</p>
<p><strong>Background</strong></p>
<p>I have a <code>toggleButton</code> on a Fragment(named homeFragment). It shows <em>Stop</em> text <code>if(toggleButton.isChecked)</code>, else it shows <em>Start</em> text.
This <code>toggleButton</code> starts and stops a Service. </p>
<p>Now, there are two ways to stop this service. One is to tap on <code>toggleButton</code> again(which stops the service) and, the other is through Service itself.</p>
<p>When this service is started, <code>toggleButton</code> shows 'Stop' text.
This service creates a Sticky Notification and calls <code>this.stopSelf</code> after that.
This Notification has a button close this notification.
This option calls a <code>BroadcastReceiver</code> to stop/cancel the notification.</p>
<p><strong>Problem/Requirement</strong></p>
<p>Now, when the service is closed through notification button, If app is visible or in the foreground, I want to trigger that <code>toggleButton</code> on Fragment to show <em>Start</em> text again.
I don't need to handle this if appActivity is in background/paused/closed (i take care of that through checking <code>sharedPrefs</code> in <code>onCreate()</code>)</p>
<p><strong>I tried:</strong></p>
<ol>
<li><p>Using a Boolean SharedPref Key(say <code>isServiceRunning</code>) which keeps track of service state. In <code>onCreate()</code>, I save a <code>true</code> boolean. In <code>onDestoy()</code>, I save a <code>false</code> boolean.
And then, I register a <code>onSharedPreferencesChangeListener</code> to <code>sharedPrefs(inside fragment)</code> which checks if <code>isServiceRunning</code>'s sharedPrefkey is changed or not.
And, if it is, it calls <code>toggleButton.setChecked(false);</code></p>
<p>This method rarely works. Sometimes it works, sometimes nothing happens.</p></li>
<li><p>Using a <code>LocalBroadcastReceiver</code>, but it has many errors. Like, <code>can't Instantiate Receiver: no empty method</code>. I tried to resolve,
but figured out that needs a lot of work. And, besides that accessing Fragment views inside another class is just a mess because you have to give them fragment's <code>layout</code>
which can be <code>null</code> at any time. Giving this receiver class a <code>View</code> element from <code>onViewCreated()</code> is difficult. I tried inflating the <code>layout</code> + <code>findViewById</code> to do this,
but no success/error.</p>
<p>This method never worked, i think it is not efficient.</p></li>
<li><p>Using <code>static</code> variables everywhere. So, i made a global <code>View</code> element(say <code>activeLayout</code>).
It is <code>private</code> and <code>static</code>, so that a <code>static</code> method(which toggles the state of <code>toggleButton</code>) can access layout of fragment.
<code>activeLayout</code> is assigned a Layout from <code>onViewCreated()</code> method.</p>
<p>Now, if i call this <code>static</code> method from my <code>stopNotificationReceiver</code>, it works(i only checked two times). But, a new Warning is shown that:</p>
<blockquote>
<p><strong>Warning:</strong> Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)</p>
</blockquote>
<p>So, i can't make <code>activeLayout</code> as a <code>static</code> variable, which breaks this whole idea.</p></li>
</ol>
<p>Please suggest me an alternative if i am doing it all wrong. Or correct me on how to do this.</p>
| <p>Use a broadcast reciver and register it in your fragment</p>
<p>You can call Broadcast reciver by using below code inside ur service </p>
<pre><code>Intent intent = new Intent();
intent.putExtra("extra", cappello);
intent.setAction("com.my.app");
sendBroadcast(intent);
</code></pre>
<p>In your Fragment implement a BroadcastReceiver :</p>
<pre><code>private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String state = extras.getString("extra");
updateView(state);// update your textView in the main layout
}
}
</code></pre>
<p>and register it in onResume() of Fragment:</p>
<pre><code>IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.my.app");
receiver = new MyBroadcastReceiver();
registerReceiver(receiver, intentFilter);
</code></pre>
|
iOS: App doesn't work after a while (parallel installation of Xcode 8) <p>I used XCode 7.3 for a long time and have developed a game for my wife. Today when recompiling and starting it on the iPhone I get an error:</p>
<pre><code>dyld: Library not loaded: @rpath/libswiftAVFoundation.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/797B62E4-4355-4FA7-A56A-90633DF2E16D/Dirks Letter Puzzle.app/Dirks Letter Puzzle
Reason: no suitable image found. Did find:
/private/var/mobile/Containers/Bundle/Application/797B62E4-4355-4FA7-A56A-90633DF2E16D/Dirks Letter Puzzle.app/Frameworks/libswiftAVFoundation.dylib: code signature invalid for '/private/var/mobile/Containers/Bundle/Application/797B62E4-4355-4FA7-A56A-90633DF2E16D/Dirks Letter Puzzle.app/Frameworks/libswiftAVFoundation.dylib'
</code></pre>
<p>I don't have any idea what it means. It ran fine for month (after updating signing). Meanwhile I installed XCode 8 as a separate App to keep 7.3 for this app. I never changed or updated my little game. So sources are still the same. The iPhone is the same. What happend and how can I get it back to run?</p>
| <p><em>posting this answer from my comment</em></p>
<blockquote>
<p>1) Make sure only one of the Xcodes is open at a time. </p>
<p>2) Do a clean (command shift k), and clean the build folder (option
command shift k).</p>
</blockquote>
|
GTX with maven project creation <p>im trying to create a maven project with GTX. Im following this tutorial: <a href="https://www.youtube.com/watch?v=5QPOAXLGB2Y" rel="nofollow">https://www.youtube.com/watch?v=5QPOAXLGB2Y</a>, but i get error after I create project:</p>
<pre><code>Failed to read artifact descriptor for com.sencha.gxt:gxt-chart:jar:4.0.2
Failed to read artifact descriptor for com.sencha.gxt:gxt-theme-neptune:jar:4.0.2
</code></pre>
<p>I have no experience with maven, so I would be glad if someone explained me what it is about</p>
| <p>You are using the commercial version of Sencha GXT (4.0.2). In this case you need credentials to log in the repository. I think, that's your problem.</p>
<p>More informations can be found here:
<a href="http://docs.sencha.com/gxt/4.x/getting_started/maven/Maven.html" rel="nofollow">http://docs.sencha.com/gxt/4.x/getting_started/maven/Maven.html</a> </p>
|
Which functions should I use to url safe search redirect <p>I have a search input, and a redirection function in jQuery, which redirects users when they hit enter to search.</p>
<pre><code><input type=text class=searcher>
</code></pre>
<pre class="lang-js prettyprint-override"><code>$(".searcher" ).keypress(function (e) {
var searcher = $('.searcher').val();
if (searcher.length>2 && e.which == 13) {
document.location = 'http://www.example.com/?q=' + searcher;
}
});
</code></pre>
<p>However, I need to know the functions I should add to make it url safe search redirect ? (Means that changing query to URL safe if it contains <code>'</code>, <code>"</code>, <code>\</code>, <code>&</code>, <code>+</code> which breaks the script)</p>
| <p>You don't even need JavaScript.</p>
<pre><code><form action="http://www.example.com/" method="get">
<input type="search" name="q" minlength="3" />
</form>
</code></pre>
<p>The browser will take care of <em>everything</em> here. Even submitting the form: when a form contains only one input element, then the default action of hitting Enter in it is to submit the form.</p>
|
Basic Method Calling - Max Integer <p>I have one public method and the method receives two numbers for example 2 and 7, how do I make it so that the method answers with the largest number i.e 7</p>
<pre><code>public class Test {
public static void main(String[] args) {
int max(int x ,int y) {
int x = 2;
int y = 7;
return y > x;
}
}
}
</code></pre>
<p>Is what i've gotten so far.</p>
| <p>You could use Java's methods...</p>
<p>More practically: Java has a library called Math. Math has a static function that gives the max number between two numbers.</p>
<pre><code>Math.max(firstNum, secondNum);
</code></pre>
<p>You can use this.</p>
|
Arraysort f# not giving wanted type <p>I've created a function that sorts an array by converting it to a list first (might be a little silly, but that's my solution whatsoever). Anyways, it doesn't show up with the type like other similar sort functions does. I'd like it to look like <code>sort : (âa [] -> âa []) when âa : comparison</code>. Mine goes:</p>
<pre><code>val arraySort : array:int [] -> int []
val it : unit = ()
</code></pre>
| <p>First step, remove all type annotation ; you normally put it only when needed (ie when inference can't determine things without a little help)
Second step use function inside module (here Array module) that way (among other things) inference can determine what is the array using the signature of those functions</p>
<p>That gives :</p>
<pre><code>let rec putNumber (thelist, value) =
match thelist with
| [] -> [value]
| x :: xs -> if value <= x
then [value; x] @ xs
else x :: putNumber (xs, value)
let sort array =
let rec sortList array blist index =
let clist = putNumber (blist, Array.get array index)
if index < Array.length array - 1
then sortList array clist (index + 1)
else clist
List.toArray (sortList array [] 0)
</code></pre>
<p>That said, without changing the algorithm (although it's not really efficient) things can be written a little more idiomatically :</p>
<pre><code>let rec putNumber value = function
| [] -> [value]
| x :: xs when value <= x -> [value; x] @ xs
| x :: xs -> x :: putNumber value xs
let sort array =
let len = Array.length array
let rec sortList blist index =
let value = Array.get array index
let clist = putNumber value blist
if index < len - 1
then sortList clist (index + 1)
else clist
sortList [] 0
|> List.toArray
</code></pre>
|
C# - text file with matrix - divide all entries <p>I have a <strong>text</strong> file with a 1122 x 1122 matrix of precipitation measurements.
Each measurement is represented with 4 decimal digits.
Example lines look like this:</p>
<p>0.0234 0.0023 0.0123 0.3223 0.1234 0.0032 0.1236 0.0000 ....</p>
<p>(and this 1122 values long and 1122 lines down.</p>
<p>I need this same text file, but with all values <strong>divided by 6</strong>.
(and I have to do this for 920 files like that....)</p>
<p>I managed to do this, but in a no doubt atrociously ineffective and memory exhaustive way:</p>
<ol>
<li>I open the textfiles one by one and read each text file line by line</li>
<li>I split each line into a string array with the separate values as members</li>
<li>I go through the array, converting each value to double, divide by 6 and convert the result back to string, formatted with 4 decimal digits and store as member in a new string array.</li>
<li>I join the array back to a line</li>
<li>I write this line to a new text file.</li>
<li>Voila (after an hour or so...) I have my 920 new text files.</li>
</ol>
<p>I am sure there is a much faster and professional way to do this. I have looked at endless sites about Matrix.Divide but don't see (or understand) a solution there for this problem.
Any help will be appreciated!
This is a code snippet as used for each file:</p>
<pre><code>
foreach (string inputline in inputfile)
{
int count = 0;
string[] str_precip = inputline.Split(' '); // holds string measurements
string[] str_divided_precip = new string[str_precip.Length]; // will hold string measurements divided by divider (6)
foreach (string measurements in str_precip)
{
str_divided_precip[count] = ((Convert.ToDouble(measurements)) / 6).ToString("F4", CultureInfo.CreateSpecificCulture("en-US"));
count++;
}
string divline = string.Join(" ", str_divided_precip);
using (System.IO.StreamWriter newfile = new System.IO.StreamWriter(@"asc_files\divfile.txt", true))
{
newfile.WriteLine(divline);
}
}
</code></pre>
| <p>Assuming the files are well-formed, you should essentially be able to process them a character at a time without needing to create any arrays or do any complicated string parsing.</p>
<p>This snippet shows the general approach:</p>
<pre><code>string s = "12.4567 0.1234\n"; // just an example
decimal d = 0;
foreach (char c in s)
{
if (char.IsDigit(c))
{
d *= 10;
d += c - '0';
}
else if (c == ' ' || c == '\n')
{
d /= 60000; // divide by 10000 to get 4dps; divide by 6 here too
Console.Write(d.ToString("F4"));
Console.Write(c);
d = 0;
}
else {
// no special processing needed as long as input file always has 4dp
Debug.Assert(c == '.');
}
}
</code></pre>
<p>Clearly you would be writing to a (buffered) file stream instead of the console.</p>
<p>You could probably roll your own faster version of <code>ToString("F4")</code> but I doubt it would make a significant difference to the timings. But if you can avoid creating a new array for each line of the input file by using this approach, I'd expect it to make a substantial difference. (In contrast, one array per file as a buffered writer is worthwhile, especially if it is declared big enough from the start.)</p>
<p><strong>Edit</strong> (<em>by Sani Singh Huttunen</em>)<br>
Sorry for editing your post but you are absolutely correct about this.<br>
Fixed point arithmetics will provide a significant improvement in this case.</p>
<p>After introducing <code>StreamReader</code> (~10% improvement), <code>float</code> (another ~35% improvement) and other improvements (yet another ~20% improvement) (see comments) this approach takes ~12 minutes (system specs in my answer):</p>
<pre><code>public void DivideMatrixByScalarFixedPoint(string inputFilname, string outputFilename)
{
using (var inFile = new StreamReader(inputFilname))
using (var outFile = new StreamWriter(outputFilename))
{
var d = 0;
while (!inFile.EndOfStream)
{
var c = (char) inFile.Read();
if (c >= '0' && c <= '9')
{
d = (d * 10) + (c - '0');
}
else if (c == ' ' || c == '\n')
{
// divide by 10000 to get 4dps; divide by 6 here too
outFile.Write((d / 60000f).ToString("F4", CultureInfo.InvariantCulture.NumberFormat));
outFile.Write(c);
d = 0;
}
}
}
}
</code></pre>
|
Transfer JavaScript to jquery not working <p>I collect a script to display facebook type multiply chat box. In this JavaScript code I used a Iframe to load chat page. But now a want to avoid iframe, and I am not enough knowledge about JavaScript. </p>
<p>So have any way to load my chat page by JavaScript for this script. OR if I transfer this script at jquery where is my problem below please?</p>
<p>JavaScript :</p>
<pre><code>function register_popup(id, name, cmd, pmd)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '<div class="popup-box chat-popup cy'+id+'" id="'+ id +'">';
//if avoid iframe how to load chat page
element = element + '<div class="popup-messages"><iframe src="../chat.php?u='+ cmd +'" frameborder="0" id="iFrame1" name="CmainFrame" width="100%" height="249" style="overflow:hidden" class="if'+ cmd +'"></div></div>';
document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
popups.unshift(id);
calculate_popups();
}
function calculate_popups()
{
var width = window.innerWidth;
if(width < 540)
{
total_popups = 0;
}
else
{
width = width - 200;
//320 is width of a single popup box
total_popups = parseInt(width/320);
}
display_popups();
}
function display_popups()
{
var right = 220;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
var element = document.getElementById(popups[iii]);
element.style.right = right + "px";
right = right + 320;
element.style.display = "block";
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
var element = document.getElementById(popups[jjj]);
element.style.display = "none";
}
}
//recalculate when window is loaded and also when window is resized.
window.addEventListener("resize", calculate_popups);
window.addEventListener("load", calculate_popups);
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
</code></pre>
<p>Tried as jquery:</p>
<pre><code> function register_popup(id, name, cmd, pmd)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups(); //alert(popups(id));
return;
}
}
$("<div></div>").attr('id',id).append('<div class="popup-box chat-popup cy'+id+'" id="'+ id +'"><div class="popup-messages"><div id="iFrame1" name="CmainFrame" width="100%" height="249" style="overflow:hidden" class="if'+ cmd +'"><object type="text/html" data="../chat.php?u='+ cmd +'"></div></div></div>');
popups.unshift(id);
calculate_popups();
}
function display_popups()
{
var right = 220;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
right = 220 + 320;
$("#"+popups[iii]).css({"display": "block", "right": "right"}).show();
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
$("#"+popups[jjj]).css("display", "none");
}
}
//others function remain same
</code></pre>
| <p>I didn't closely analyse your code, but I did notice this:</p>
<pre><code>$("<div></div>").attr('id',id).append('<div class="popup-box chat-popup cy'+id+'" id="'+ id +'"><div class="popup-messages"><div id="iFrame1" name="CmainFrame" width="100%" height="249" style="overflow:hidden" class="if'+ cmd +'"><object type="text/html" data="../Cchat.php?u='+ cmd +'"></div></div></div>');
</code></pre>
<p>I don't know what you <em>think</em> that is going to do, but what it does do is create a div, assign it an id, give some children, and then throw the whole thing away. Did you want to insert it somewhere?</p>
<p><strong>Edit:</strong></p>
<p>For example, you could write:</p>
<pre><code>$("body").append('<div class="popup-box chat-popup cy'+id+'"...
</code></pre>
<p>(Find the body and insert in the new div at its bottom.)</p>
<p>or </p>
<pre><code>$("#" + id).append('<div class="popup-box chat-popup cy'+id+'"...
</code></pre>
<p>(Find the existing div with the given ID append the new div to it.)</p>
|
python: numpy-equivalent of list.pop? <p>Is there a numpy method which is equivalent to the builtin <code>pop</code> for python lists? popping obviously doenst work on numpy arrays, and I want to avoid a list conversion.</p>
| <p>There is no <code>pop</code> method for NumPy arrays, but you could just use basic slicing (which would be efficient since it returns a view, not a copy):</p>
<pre><code>In [104]: y = np.arange(5); y
Out[105]: array([0, 1, 2, 3, 4])
In [106]: last, y = y[-1], y[:-1]
In [107]: last, y
Out[107]: (4, array([0, 1, 2, 3]))
</code></pre>
<p>If there were a <code>pop</code> method it would return the <code>last</code> value in <code>y</code> and modify <code>y</code>.</p>
<p>Above, </p>
<pre><code>last, y = y[-1], y[:-1]
</code></pre>
<p>assigns the last value to the variable <code>last</code> and modifies <code>y</code>.</p>
|
Forgot Password Form <p>I want to add a Forgot Password form for when the user clicks Forgot Password. I already have one in PHP. I am using a MySQL database. </p>
<p>Should it go to the Forgot Password Activity? </p>
<p>Can anyone help me or have a sample code?</p>
| <p>To send an email, you can use this:</p>
<pre><code>Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "emailaddress@emailaddress.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
</code></pre>
<p>P.S. taken from <a href="http://stackoverflow.com/questions/8701634/send-email-intent" title="here">here</a></p>
|
If statement condition where element equals element <p>I am testing a web page that contains a table. You can click a "Create new" link to add records to the grid. Once "Create New" is clicked, a dialog appears with some text boxes, another grid and a Cancel and Save button. You can then click a link to add a record to the dialog's grid which makes another dialog appear with text boxes and a Cancel and Save button. At my test level class, I currently click on these buttons then wait for the dialog's to open or close. I need to formulate a generic method which encompasses both the click and the wait, for each and every button. So instead of 2 lines of code at my test level to click an element and wait for a window, I would have one line of code that handles that. Below is my dilemma:</p>
<p>I need to be able to apply an <code>If</code> condition where a passed parameter of <code>IWebElement</code> equals a certain <code>IWebElement</code>, but it does not allow me to do this. The <code>if</code> statement doesn't find a match for some reason, so code inside the <code>if</code> statement never gets reached. Am I missing something? If not, is there a workaround? </p>
<p>NOTE: Using <code>button.text == SaveOrganizationBtn.Text</code> is a workaround, but would fail in my specific case, because some of these buttons might not have been loaded into the HTML for a certain test (i.e. A form has not been invoked), so the <code>if</code> statement fails. It would never be able to grab the <code>Text</code> property because it cant find the element in the first place.</p>
<p>Example code:</p>
<pre><code>ClickButton(SaveNetworkBtn);
public void ClickButton(IWebElement button)
{
if (button == SaveOrganizationBtn)
{
SaveOrganizationBtn.Click();
WaitForOrganizationFormToClose();
}
if (button == SaveNetworkBtn)
{
SaveNetworkBtn.Click();
WaitForNetworkFormToClose();
}
</code></pre>
| <p>Use the <code>Equals()</code> method for your scenario. <code>==</code> will not work for this. you need to check it as <code>if(button.Equals(SaveOrganizationBtn))</code>. The result for this will be <code>true</code>, if it is the same object else it will return false.</p>
<p>I hope, it will help you.</p>
|
Reading data from a text file into a struct with different data types c# <p>I have a text file that stores data about cars, its call car.txt. I want to read this text file and categorize each of the sections for each car. Ultimately I want to add this information into a doubly linked list. So far everything I have tried is either giving me format exception or out of range exception.
This is my public structure</p>
<pre><code>public struct cars
{
public int id;
public string Make;
public string Model;
public double Year;
public double Mileage;
public double Price;
}
</code></pre>
<p>This is where I try reading the data into the struct then add it to the DLL</p>
<pre><code>static void Main()
{
int Key;
cars item = new cars();
int preKey;
/* create an empty double linked list */
DoubleLinkedList DLL = new DoubleLinkedList();
string line;
StreamReader file = new StreamReader(@"C:\Users\Esther\Desktop\cars.txt");
while ((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
var array = line.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
item.Make =array[0];
item.Model = array[1];
item.Year = Double.Parse(array[2]);
item.Mileage = Double.Parse(array[2]);
item.Price = Double.Parse(array[2]);
// Using newline to seprate each line of the file.
Console.WriteLine(line);
DLL.AppendToHead(item);
}
</code></pre>
<p>This is throws a format exception then an out of range exception. How do I get this code to read the text file into the struct and add it to my DLL? This is the car.txt file</p>
<pre><code> BMW
228i
2008
122510
7800
Honda
Accord
2011
93200
9850
Toyota
Camry
2010
85300
9500
</code></pre>
| <p>You are reading the file line by line with <code>ReadLine</code>, and trying to split a single line with a line ending. This will result in an array with just one element (E.G. "BMW")</p>
<p>You can either read the whole file and then split by lines or just assume that each line will contain some data.</p>
<p>The <code>OutOfRangeException</code> refers to your invocation of <code>array[1]</code> when the array contains only <code>array[0] = "BMW"</code>.</p>
|
Background black when programmatically setting activity background <p>I have a fullscreen activity, for which I want to programmatically set the background. I have four different images in my drawable folder, and each time the activity is created, I want to randomly choose one for the background. Here is my code:</p>
<pre><code>LayoutInflater inflater = getLayoutInflater();
FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.activity_my, null);
int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4};
Random rand = new Random();
layout.setBackgroundResource(images[rand.nextInt(images.length)]);
</code></pre>
<p>Here is the XML file:</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.mkessler.MyApp.MyActivity">
<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:id="@+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="@color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent">
<Button
android:id="@+id/dummy_button"
style="?metaButtonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unimportant text"
android:onClick="someFunction"/>
</LinearLayout>
</FrameLayout>
</code></pre>
<p></p>
<p>However, when I run the app on my phone, the background is just black. The same happens when I try to set it using a specific one of the images. Needless, when I set it from the XML file it works fine.</p>
<p>EDIT:
Just to clarify, even when I try to set it to a given image programmatically and not though the XML file, I get a black background. I think focusing on the random aspect of the question isn't going to get anywhere.</p>
<p>EDIT #2: Minimum API of my project set to 15. Don't know if this is relevant, but in case anyone thinks it matters...</p>
| <p>Don't get view via <code>LayoutInflater</code>, if your <code>Activity</code> has xml layout and you called <code>setContentView(int resId)</code> you just find your root view and set background.</p>
<pre><code>FrameLayout layout = (FrameLayout) findViewById(...);
layout.setBackgroundResource(images[rand.nextInt(images.length)]);
</code></pre>
<p>If you want to get view via <code>LayoutInflater</code> :</p>
<pre><code>LayoutInflater inflater = getLayoutInflater();
FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.activity_my, null);
layout.setBackgroundResource(images[rand.nextInt(images.length)]);
setContentView(layout);
</code></pre>
|
IdentityServer4 and Web API .NET 4.6.2 <p>Is there a OWIN middleware that can work with a standard .NET 4.6.2 (not Core) framework to valide tokens coming from IdentityServer4. </p>
<p>Something like
<a href="https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation" rel="nofollow">https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation</a></p>
| <p>Even though the project README.md says <code>OWIN Middleware to validate access tokens from IdentityServer v3</code>. It should in theory still work with IDS4 tokens:</p>
<p><a href="https://github.com/IdentityServer/IdentityServer3.AccessTokenValidation" rel="nofollow">https://github.com/IdentityServer/IdentityServer3.AccessTokenValidation</a></p>
|
Cannot communicate between fragment and activity <p>I have a dialogFragment where there's an edit text. I would like to pass the text to the parent activity, when the positive button of the dialog is clicked, but it doesn't seem to call the method of the interface implemented in the activity.
Code:
DialogFragment</p>
<pre><code> @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setView(R.layout.fragment_newfile);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onFileTyped(textNewFile.getText().toString());
Log.w("Positive","Button"); //This log is showed
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
</code></pre>
<p>MainActivity</p>
<pre><code> @Override
public void onFileTyped(String fileName) {
Log.w("New File", ""); //This log is not showed
MainFragment frag = (MainFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
File newFile = new File(frag.getCurrentDir().getAbsolutePath(), "fileName");
}
</code></pre>
<p>Listener assignment</p>
<pre><code> @Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof onFileTypedListener) {
listener = (onFileTypedListener) activity;
} else {
throw new RuntimeException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
</code></pre>
| <p>I tried your code and it works in my case. Displays both log messages when clicked on positive button. Compare my code with yours and see if there is anything different:</p>
<p>Activity:</p>
<pre><code>public class DialogFragmentActivity extends AppCompatActivity implements MyDialogFragment.onFileTypedListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialogfragment);
MyDialogFragment.newInstance("title").show(getSupportFragmentManager(),"MyDialogFragment");
}
@Override
public void onFileTyped(String txt) {
Log.w("yay", "it works");
}
}
</code></pre>
<p>Fragment:</p>
<pre><code>public class MyDialogFragment extends DialogFragment {
onFileTypedListener listener;
public interface onFileTypedListener{
public void onFileTyped(String txt);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setView(R.layout.fragment_newfile);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onFileTyped("hello");
Log.w("Positive","Button"); //This log is showed
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof onFileTypedListener) {
listener = (onFileTypedListener) activity;
} else {
throw new RuntimeException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
public static MyDialogFragment newInstance(String title) {
Bundle args = new Bundle();
args.putString("title",title);
MyDialogFragment fragment = new MyDialogFragment();
fragment.setArguments(args);
return fragment;
}
}
</code></pre>
|
Function EVP_aes_256_ctr not found when compiling with OpenSSL on a Mac <p>I've been trying to compile some files using the "make" command on a directory. However, I keep getting this error:</p>
<pre><code>Sammys-MacBook-Pro:p1 AlphaMale$ make
gcc -L/usr/local/lib/ -o kem-enc ske.o rsa.o kem-enc.o prf.o -lcrypto -lssl -lgmp
Undefined symbols for architecture x86_64:
"_EVP_aes_256_ctr", referenced from:
_ske_encrypt in ske.o
_ske_decrypt in ske.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [kem-enc] Error 1
</code></pre>
| <p>The error message is (in the relevant part):</p>
<pre><code>Undefined symbols for architecture x86_64:
"_EVP_aes_256_ctr", referenced from:
_ske_encrypt in ske.o
_ske_decrypt in ske.o
</code></pre>
<p>telling you that the function <code>EVP_aes_256_ctr</code> is not found in the version of OpenSSL that you're using. Did you try a Google search on, say, 'openssl evp_aes_256_ctr'? If so, say so. If not, do so. If you look in the most recent documentation (<a href="https://www.openssl.org/docs/man1.1.0/crypto/" rel="nofollow">OpenSSL 1.1.0</a>), you can find a number of <code>EVP_aes_256_</code><em><code>xyz</code></em> functions, but <code>EVP_aes_256_ctr()</code> is not one of them.</p>
<p>So, you have to track down who thought that the function existed and where they found it. The <a href="https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation" rel="nofollow">encryption modes</a> (the <em><code>xyz</code></em> values) that are listed in the OpenSSL docs include: <code>cbc</code>, <code>ccm</code>, <code>cfb</code>, <code>ecb</code>, <code>gcm</code>, <code>ofb</code> â and not <code>ctr</code> â mildly surprising, but apparently so.</p>
<p>You could check the source to see whether it is available but undocumented. Looking in the source from <code>openssl-1.1.0b.tar.gz</code>, I can find:</p>
<pre><code>./include/openssl/evp.h:780:const EVP_CIPHER *EVP_aes_256_ecb(void);
./include/openssl/evp.h:781:const EVP_CIPHER *EVP_aes_256_cbc(void);
./include/openssl/evp.h:782:const EVP_CIPHER *EVP_aes_256_cfb1(void);
./include/openssl/evp.h:783:const EVP_CIPHER *EVP_aes_256_cfb8(void);
./include/openssl/evp.h:784:const EVP_CIPHER *EVP_aes_256_cfb128(void);
./include/openssl/evp.h:785:# define EVP_aes_256_cfb EVP_aes_256_cfb128
./include/openssl/evp.h:786:const EVP_CIPHER *EVP_aes_256_ofb(void);
./include/openssl/evp.h:787:const EVP_CIPHER *EVP_aes_256_ctr(void);
./include/openssl/evp.h:788:const EVP_CIPHER *EVP_aes_256_ccm(void);
./include/openssl/evp.h:789:const EVP_CIPHER *EVP_aes_256_gcm(void);
./include/openssl/evp.h:790:const EVP_CIPHER *EVP_aes_256_xts(void);
./include/openssl/evp.h:791:const EVP_CIPHER *EVP_aes_256_wrap(void);
./include/openssl/evp.h:792:const EVP_CIPHER *EVP_aes_256_wrap_pad(void);
./include/openssl/evp.h:794:const EVP_CIPHER *EVP_aes_256_ocb(void);
./include/openssl/evp.h:797:const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void);
./include/openssl/evp.h:799:const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void);
</code></pre>
<p>Note line 787! So, in some versions of OpenSSL, the function is partially known (I didn't spot the implementation of the function) but it is not formally documented in the OpenSSL documentation on the OpenSSL web site.
Having said that, tracking the source of <code>EVP_aes_256_cbc</code> is not trivial, so tracking the source of <code>EVP_aes_256_ctr</code> is equally fiddly. Looking in my own build of OpenSSL 1.0.2h (update needed), I find <code>EVP_aes_256_ctr()</code> and <code>EVP_aes_256_cbc()</code> defined in object file <code>e_aes.o</code> in the library. There are mentions of <code>ctr</code> in the source of <code>crypto/evp/e_aes.c</code>, but working out exactly how <code>EVP_aes_256_ctr</code> gets to be in the object file is ⦠challenging (as in: "I've not worked out how, yet").</p>
|
Transform JSON array and assign to single value case class with Play JSON <p>Given the following JSON object:</p>
<pre><code>{realtime-accesses: [
{realtime-access: {
level: 2
marketID: 1
}},
{realtime-access: {
level: 4
marketID: 3
}}
]
}
</code></pre>
<p>I want a Scala object that looks like this:</p>
<pre><code>RealTimeAccesses(Map(1->2,3->4))
</code></pre>
<p>This is the code Im trying to use:</p>
<pre><code> case class RealTimeAccesses(markets: Map[Int, Int])
object RealTimeAccesses {
implicit val realTimeAccessesFormatter: Format[RealTimeAccesses] = (
(__ \ "realtime_accesses").format[List[Map[String, Map[String, Int]]]].map(
_.iterator
.flatMap(_.values)
.map { v => v("marketID") -> v("level") }
.toMap).inmap(m => RealTimeAccesses(m), (m: RealTimeAccesses) => m.markets))
}
</code></pre>
<p>However this does not work, im getting can not resolve symbol on <code>inmap</code>.</p>
<p>My questions are:</p>
<ol>
<li>How can this transformation be done the way I want?</li>
<li>Is it possible to use <code>type RealTimeAccess = Map[Int,Int]</code> instead of a case class?</li>
</ol>
| <p>The reason why it doesn't work is that <code>Format[A]</code> does not have a functor. When you call <code>map</code> on it with a function <code>A => B</code> you are getting back <code>Reads[B]</code> not a <code>Format[B]</code>. </p>
<pre><code>val format1: Format[List[Map[String, Map[String, Int]]]] = (__ \ "realtime_accesses").format[List[Map[String, Map[String, Int]]]]
val format2: Reads[Map[Int, Int]] = format1.map(
_.iterator
.flatMap(_.values)
.map { v => v("marketID") -> v("level") }
.toMap
)
</code></pre>
<p>So you need to call <code>.inmap</code> immediately and do all necessary transformation inside of <code>inmap</code>.</p>
<pre><code>(__ \ "realtime_accesses").format[List[Map[String, Map[String, Int]]]].inmap(
m => {
val markets = m.flatMap(_.values)
.map { v => v("marketID") -> v("level") }
.toMap
RealTimeAccesses(markets)
},
(m: RealTimeAccesses) => m.markets.map {
case (marketID, level) =>
Map("realtime-access" ->
Map(
"marketID" -> marketID,
"level" -> level
))
}.toList
)
</code></pre>
|
How to edit and read specific lines of a text document with a Batch script <p>I am writing a Batch text adventure at the moment, and I am attempting to find a way to make a world save and also save the various bits of armor and the statistics they have onto a text document. I am at a loss for how to do this, and I was wondering if anyone could help.</p>
<p>By the way, I mean the actual Batch Scripting Language, on it's own. I do not mean things like PowerShell or VBScript, although, if this Batch turns out to not be worth it, I might switch to it for continued development.</p>
<p>Thanks!</p>
| <p>Depending on how you have the script setup. If you are having the info set as variables like %armor% or w.e you can use set out. Here is an example,</p>
<pre><code>@Echo Off
set /p armor=
Set "out=C:\users\*your login name*\Desktop"
> "%out%\YourFileName.txt" %armor%
</code></pre>
<p>Then whatever the armor variable is set it will be put in the text document. Not sure if this is sufficent as I am fairly new to messing with scripts myself but hope it helps!</p>
|
CoreData iCloud changes not saved <p>I m making an app with CoreData and iCloud integration. I went through the <a href="https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/UsingCoreDataWithiCloudPG/UsingSQLiteStoragewithiCloud/UsingSQLiteStoragewithiCloud.html#//apple_ref/doc/uid/TP40013491-CH3" rel="nofollow">Apple Documentation</a> to adapt my already working app to integrate iCloud synchronization. </p>
<p>Inserting objects and deleting seems to be working fine. When I delete the app and reinstall it on my phone all synchronized data are correctly restored. </p>
<p>My issue is when I modify an NSManagedObject. The context which I used to query CoreData to fetch my object does not detect any changes on my objects when I modify a field. Therefore the context is not saved. If I try to force saving context even when no changes are detected, nothing is saved. </p>
<p>I went through stack oververflow and found that the context must have a stalenessInterval set to 0.0. This did nothing to my app. Do you have any idea on what could be wrong ? </p>
<p>I noticed that the context carried by the NSManagedObject seems different than the one I used to fetch data. If I call save method on this context, nothing happened either. </p>
<p>I am completely lost, since I thought it would ba as easy as inserting and deleting objects.</p>
<p>Thanks for your help ! </p>
<p>(ps: I code with Swift but even Objective C code is acceptable as answer :) )</p>
| <p>I was actually trying to use two databases whereas I should have used configurations to separate entities saved to the cloud and those saved locally. </p>
<p>For those who wants more information on CoreData with iCloud i suggest to go through this <a href="https://developer.apple.com/videos/play/wwdc2012/227/" rel="nofollow">video</a> from Apple WWDC 2012 which helps a lot getting into this subject. </p>
|
What is the purpose of repository when service classes can do the same? <p>Normally I put the logic in the service classes without using repository, for example, something like this:</p>
<pre><code>namespace App\ProjectName\Profile;
use App\User;
class AccountService
{
private $userModel;
public function __construct(User $userModel)
{
$this->userModel = $userModel;
}
public function detail()
{
$user = \Auth::User();
return [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'keys' => $user->keys,
];
}
public function addKey($name, $key)
{
return $this->userModel->keys()->create([
'name' => $name,
'key' => $key
]);
}
}
</code></pre>
<p>I have seen some example out there, refactored even further by creating repository classes. something like <code>UserController</code> inputs data, sends it to <code>UserCreatorService</code>, which gets the <code>UserRepository</code> which in turn gets the <code>UserModel</code>. It seem <code>UserCreatorService</code> is a repeat of <code>UserRepository</code>?</p>
| <p>From DDD (Domain Driven Design) the responsibility of a repository is to take care of loading, storing, modifying and deleting an entity on the designated data storage (which may or may not be a database -- it may even be a remote server or just a file).</p>
<p>A service, on the other hand, has (or should have) a very narrow responsibility of performing some useful activity. Each service is instantiated separately and then injected into code in the application layer or above, which acts as a bridge (Bridge pattern). This approach has proven to be very advantageous because it allows to manage the dependencies between otherwise unrelated (uncoupled) code.</p>
<p>Those two definitions and the origin of the concepts shows that they actually are very different things. By <em>pure chance</em> you noticed that a repository and a service have an apparent overlap, but that's due to implementation details or plain misuse. Their responsibilities may under circumstances go hand in hand (giving rise to a collaboration) but they really are orthogonal concepts.</p>
<p>Furthermore, Repositories should arise from a deep layer (Persistance or DAL, Data Access Layer). Services, on the other hand, often are vertical cross-cutting or arise on the application layer.</p>
<p>Through proper layering the differences between repositories and services become even more apparent.</p>
<blockquote>
<p>Do not think about them as pure code artifacts you can move around. They are well-defined concepts useful to understand about and design the structure of a system. They decline into actual code only as a consequence of that design.</p>
</blockquote>
<p>I hope I succeeded in writing something that clears up some ideas and is not confusing.</p>
|
PHP ftp_put fails with "Warning: ftp_put (): PORT command successful" <p>File is created on the FTP server, but its always 0 bytes large. Please give me a solution so that the file upload will working success. </p>
<p>I keep getting this warning:</p>
<blockquote>
<p>Warning: ftp_put (): PORT command successful in C: \ xampp \ htdocs \ mailing \ teskirim-file-simpan2.php on line 30<br>
FTP upload has failed!</p>
</blockquote>
<p><img src="http://i.stack.imgur.com/Htila.jpg" alt="enter image description here"></p>
<p>My script is:</p>
<pre><code><?php
$ftp_server = "********";
$ftp_serverpath = "ftp.".$ftp_server;
$ftp_user_name = "********";
$ftp_user_pass = "***********";
$email_dir = "*******@*********";
$nyambungkeftp = ftp_connect($ftp_server);
if (false === $nyambungkeftp) {
throw new Exception('Unable to connect');
}
$loggedInnyambungkeftp = ftp_login($nyambungkeftp, $ftp_user_name, $ftp_user_pass);
if (true === $loggedInnyambungkeftp) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
if ((!$nyambungkeftp) || (!$loggedInnyambungkeftp)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$dest = 'detectip.txt';
$source = 'C:\xampp\htdocs\persuratan\file2\detectip.txt';
echo $dest;
echo $source;
$upload = ftp_put($nyambungkeftp, $dest, $source, FTP_ASCII);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// close the FTP stream
ftp_close($nyambungkeftp);
?>
</code></pre>
| <p>PHP defaults to the active FTP mode. The active mode hardly ever works these days due to ubiquitous firewalls/NATs/proxies.</p>
<p>You almost always need to use the passive mode.</p>
<p>For that call the <a href="http://php.net/manual/en/function.ftp-pasv.php" rel="nofollow"><code>ftp_pasv</code></a> after the <code>ftp_login</code>:</p>
<pre><code>ftp_pasv($nyambungkeftp, true);
</code></pre>
<p>See <em>my</em> article on <a href="https://winscp.net/eng/docs/ftp_modes" rel="nofollow">FTP connection modes</a>, to understand, why you typically need to use the passive mode.</p>
|
Why does it say that the tree is null even though I inserted values? <p>I am trying to work on a binary search tree program. This is my main program. Every time I try to print Inorder traversal of the values I inserted into the tree, the printInorder function says that it's empty or null. I'm aware that the root is initialized to NULL but how do I let function know that the tree is not empty?</p>
<pre><code>void main()
{
int pgS, ch;
char chT[MAX], chT2[MAX];
treePtr root = NULL;
menu();
scanf("%d",&ch);
switch(ch)
{
case 1:
fflush(stdin);
printf("\nName of the Content: ");
gets(chT);
printf("\nPage of the content above: ");
scanf("%d",&pgS);
insert(root,pgS,chT);
system("cls");
main();
break;
case 2:
system("cls");
printInOrder(root);
Sleep(5000);
main();
break;
case 3:
printf("\nSearch Content: ");
gets(chT2);
search(root,chT2);
}
getch();
}
</code></pre>
<p>Some of the functions, maybe it can help.</p>
<pre><code>treePtr insert(treePtr p, elementType noP, char *Incontent){ //insert elements in the tree
if(p==NULL) {p=createTree(Incontent,noP);}
else {
if(p->pages > noP){
p->left=insert(p->left,noP,Incontent);
p->part=Incontent;
p->pages=noP;
}
else if (p->pages <noP){
p->right=insert(p->right,noP,Incontent);
p->part=Incontent;
p->pages=noP;
}
} return p;
}
void printInOrder(treePtr p){
if (p == NULL){printf("Empty");}
else {
printInOrder(p->left);
printf("\nTABLE OF CONTENTS\n%s\t\t %d ", p->part,p->pages);
printInOrder(p->right);
}
}
</code></pre>
| <p>Your <code>insert</code> function calls <code>createTree</code> to assign a new instance to the <code>p</code> variable, but you don't assign this variable to the <code>root</code> variable in your <code>main</code> function, so <code>root</code> remains <code>NULL</code> after the function returns (i.e. <code>root = insert(root, ...)</code> would work).</p>
<p>Or, you could simply create the root node tree before calling insert (i.e. <code>root = createTree(...);</code>). Nevertheless, a <code>main</code> function recursively calling itself is a bad idea.</p>
|
I want to change an email address in Word VBA <p>In Word I would like to search the active document for @yahoo.com and replace all instances with newName@gmail.com. When I use the *@yahoo.com to find it the replace command erases all of the document before the @yahoo.com</p>
<pre><code> Sub kiffin()
With Selection.Find
.ClearFormatting
.MatchWildcards = True
.Text = "*@yahoo.com"
.Replacement.ClearFormatting
.Replacement.Text = "newName@gmail.com"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
</code></pre>
| <p>The wildcard <code>*</code> is clearly too greedy in this case, and the limited wildcard/regex support available in Word's Find functionality may not be suited for identifying individual email addresses. (Note: Word, nor RegEx is an expertise of mine).</p>
<p>If the email addresses in the Word Document are given as Hyperlinks, this can be accomplished by looping over the <code>Hyperlinks</code> collection, and checking the <code>TextToDisplay</code> for the <code>"@yahoo.com"</code> domain.</p>
<pre><code>Sub ReplaceEmailHyperlinks()
Dim newemail as String
Dim h As Hyperlink
newemail = "NewEmail@gmail.com"
For Each h In ActiveDocument.Hyperlinks
If h.TextToDisplay Like "*@yahoo.com" Then
h.TextToDisplay = newemail
h.Address = "mailto:" & newemail
End If
Next
End Sub
</code></pre>
|
Caesar Cipher Program <pre><code>def caesar_cipher(message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = positionnumber % 26
newmessage += alphabet[position]
else:
newmessage += letter
print(newmessage)
</code></pre>
<p>How can I get this to change capitals as well?</p>
| <pre><code>def caesar_cipher(message):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = positionnumber % 26
newmessage += alphabet[position]
elif letter.isupper():
positionnumber = alphabet.index(letter.lower()) + 13
position = positionnumber % 26
newmessage += alphabet[position].upper()
print(newmessage)
</code></pre>
<p>Use <code>isupper()</code> to identify capital letters</p>
|
Datatable values comparison <p>I want to get value from my datatable which has two columns. Name and OrderTime. I want to subtract corresponding value from time in a text box. I am referring to datatable values using following code. I can get result in </p>
<pre><code>string First = (mydatabaseDataSet.Tables[0].Rows[1][2].ToString());
MessageBox.Show(First);
</code></pre>
<p>But why I can't compare and get value with following code.
thanks</p>
<pre><code>private void comboBox_suburb_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox_suburb.SelectedValue!=null)
if (comboBox_suburb.SelectedItem.ToString() == mydatabaseDataSet.Tables[0].Rows[i][j].ToString())
{
int timetosub = Convert.ToInt32(mydatabaseDataSet.Tables[0].Rows[i][j + 1]);
totaltime = bdtime + timetosub;
tmpk = totaltime;
time3 = time2.AddMinutes(-tmpk);
textBox_ordertostart.Text = time3.ToString("hh:mm tt");
}
}
</code></pre>
| <p>Ok so i solved the problem.
Thanks for your feedback guys!</p>
<pre><code>private void comboBox_suburb_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\WoolsValley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\mydatabase.mdf; Integrated Security = True");
con.Open();
int i = comboBox_suburb.SelectedIndex;
int j = 1;
comboBox_suburb.ValueMember = mydatabaseDataSet.Tables[0].Columns[1].ToString();
if (comboBox_suburb.SelectedItem.ToString() == (mydatabaseDataSet.Tables[0].Rows[i][j].ToString())) ;
{
int timetosub = Convert.ToInt32(mydatabaseDataSet.Tables[0].Rows[i][j + 1]);
totaltime = bdtime + timetosub;
tmpk = totaltime;
time3 = time2.AddMinutes(-tmpk);
textBox_ordertostart.Text = time3.ToString("hh:mm tt");
}
}
</code></pre>
|
Search for address using SWIFT <p>In my app I need the user to enter his home address, but I can't get any way that the addresses that are shown are only in the users region, and are full addresses, like <code>225e 57th st, NY, New York</code>.</p>
<p>I want to give the user all the listed options on a tableview, and to filter them as the user enters his address.</p>
| <p>You can define a <a href="https://developer.apple.com/reference/mapkit/mklocalsearchcompleter" rel="nofollow">local search completer</a>:</p>
<pre><code>var completer = MKLocalSearchCompleter()
</code></pre>
<p>And then supply the query fragment:</p>
<pre><code>completer.delegate = self
completer.region = MKCoordinateRegionMakeWithDistance(currentCoordinate, 10_000, 10_000)
completer.queryFragment = "300 S Orange"
</code></pre>
<p>And implement the <code>MKLocalSearchCompleterDelegate</code> protocol</p>
<pre><code>extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
let addresses = completer.results.map { result in
result.title + ", " + result.subtitle
}
// use addresses, e.g. update model and call `tableView.reloadData()
}
}
</code></pre>
<p>And that yields:</p>
<pre>
["300 S Orange Grove Blvd, Pasadena, CA, United States",
"300 S Orange Ave, Monterey Park, CA, United States",
"300 S Orange St, Glendale, CA, United States",
"300 S Orange Dr, Los Angeles, CA, United States",
"300 S Orange Ave, Azusa, CA, United States",
"300 S Orange Grove Ave, Los Angeles, CA, United States",
"300 S Orange Ave, Brea, CA, United States",
"300 S Orange Ave, Fullerton, CA, United States",
"300 S Orange St, Orange, CA, United States",
"300 S Orange Ave, Rialto, CA, United States",
"300 S Orange Ave, Fallbrook, CA, United States",
"300 S Orange St, Escondido, CA, United States",
"300 S Orange Ave, El Cajon, CA, United States",
"300 S Orange Cir, Tulare, CA, United States",
"300 S Orange Ave, Exeter, CA, United States"]
</pre>
<hr>
<p>Or else, you can do a local search:</p>
<pre><code>let request = MKLocalSearchRequest()
request.region = MKCoordinateRegionMakeWithDistance(currentCoordinate, 10_000, 10_000)
request.naturalLanguageQuery = "300 S Pumpkin"
let search = MKLocalSearch(request: request)
search.start { response, error in
let addresses = response?.mapItems.map { item -> String in
if let addressLines = item.placemark.addressDictionary?["FormattedAddressLines"] as? [String] {
return addressLines.joined(separator: " ")
}
return item.name ?? "Unknown"
}
print(addresses)
}
</code></pre>
<p>Assuming it finds matches, that shows something like:</p>
<pre>
["300 S Pumpkin Blvd, Los Angeles, CA 92108, United States",
"300 S Pumpkin Pkwy, Los Angeles, CA 92103, United States",
"300 S Pumpkin Dr, San Gabriel, CA 91776, United States"])
</pre>
<p>Now, whether you want the <code>FormattedAddressLines</code>, or extract the individual components from the <code>addressDictionary</code> is up to you, but hopefully this illustrates the idea.</p>
|
Setting up Environment Variable for GCP <p>I read <a href="https://developers.google.com/identity/protocols/application-default-credentials" rel="nofollow">this</a> article but I still don't understand how I have to set up the environment variable with the <code>.json</code> file with the credentials. Do I have to enter something in the Terminal or write something in my Python code?</p>
<p>Also, is the path relative to the user directory? Thanks</p>
| <p>You can do either: the key part is that the environmental variable must be present for the SDK to pick up in the code that you're running. You could set it programmatically in Python (<a href="http://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python">example</a>) or in your terminal (<a href="http://stackoverflow.com/questions/234742/setting-environment-variables-in-linux-using-bash">example</a>), depending on what you want to do. You just need the process that's executing your code to have the variable set in <em>its</em> environment.</p>
<p>Use an absolute path.</p>
|
Alternate adding and subtracting a number java <p>Here's my current code: </p>
<pre><code>Scanner input = new Scanner(System.in);
int n, sum = 0;
System.out.println("Enter n:");
n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
System.out.println("The total sum is:"+sum);
</code></pre>
<p>Can someone please help to alternately add and minus an integer?</p>
<p>For example, if I enter <code>n: = 5</code> and ask the user to enter <code>4, 14, 5, 6, 1</code> then it will compute like <code>4 + 14 - 5 + 6 - 1</code></p>
| <p>You were almost there:</p>
<pre><code>for (int i = 1; i <= n; i++) {
if (i > 2 && i % 2 != 0){
sum-=input.nextInt();
} else {
sum+=input.nextInt();
}
}
</code></pre>
<p>The first two numbers contribute to the result with the "plus" sign, their sign does not alternate, hence the additional <code>i > 2</code> condition.</p>
<hr>
<p><em>Side note:</em> I would suggest renaming <code>sum</code> to <code>result</code> and changing the output text to something like <code>System.out.println("The result is:"+result);</code>.
The reason is that it's not the <em>sum</em> being calculated, to the name <code>sum</code> is a bit confusing. </p>
|
Is it possible to use component (like jButton) as an argument in a function? <p>If I am using the exact same lines of code for multiple buttons, can I use a component (in this case button) as an argument for a function instead of using a variable? That will make my work so much easier. If I have something like this:</p>
<pre><code>a1.setText("something");
a1.setBackground(Color.BLACK);
a1.setForeground(Color.WHITE);
a2.setText("something");
a2.setBackground(Color.BLACK);
a2.setForeground(Color.WHITE);
a3.setText("something");
a3.setBackground(Color.BLACK);
a3.setForeground(Color.WHITE);
</code></pre>
<p>Can I make them into one function something like:</p>
<pre><code>public void buttonFunction(Button something){
something.setText("something");
something.setBackground(Color.BLACK);
something.setForeground(Color.WHITE);
}
</code></pre>
<p>If I can, how can I?</p>
| <p>It is.
The attempt you made is the way to do this.</p>
<pre><code>public void buttonFunction(JButton something){
something.setText("something");
something.setBackground(Color.BLACK);
something.setForeground(Color.WHITE);
}
</code></pre>
<p>All you need to do is call this function after you created the JButton objects.</p>
|
Spark 2.0 DataSets groupByKey and divide operation and type safety <p>I am very much pleased with Spark 2.0 DataSets because of it's compile time type safety. But here is couple of problem that I am not able to work out, I also didn't find good documentation for this.</p>
<p><strong>Problem #1 - divide operation on aggregated column-</strong>
Consider below code -
I have a DataSet[MyCaseClass] and I wanted to groupByKey on c1,c2,c3 and sum(c4) / 8. The below code works well if I just calculate the sum but it gives compile time error for divide(8). I wonder how I can achieve following.</p>
<pre><code>final case class MyClass (c1: String,
c2: String,
c3: String,
c4: Double)
val myCaseClass: DataSet[MyCaseClass] = ??? // assume it's being loaded
import sparkSession.implicits._
import org.apache.spark.sql.expressions.scalalang.typed.{sum => typedSum}
myCaseClass.
groupByKey(myCaseClass =>
(myCaseClass.c1, myCaseClass.c2, myCaseClass.c3)).
agg(typedSum[MyCaseClass](_.c4).name("sum(c4)").
</code></pre>
<p>divide(8)). //this is breaking with exception
show()</p>
<p>If I remove .divide(8) operation and run above command it gives me below output. </p>
<pre><code> +-----------+-------------+
| key|sum(c4) |
+-----------+-------------+
|[A1,F2,S1]| 80.0|
|[A1,F1,S1]| 40.0|
+-----------+-------------+
</code></pre>
<p><strong>Problem #2 - converting groupedByKey result to another Typed DataFrame -</strong>
Now second part of my problem is I want output again a typed DataSet. For that I have another case class (not sure if it is needed) but I am not sure how to map with grouped result -</p>
<p>final case class AnotherClass(c1: String,
c2: String,
c3: String,
average: Double) </p>
<pre><code> myCaseClass.
groupByKey(myCaseClass =>
(myCaseClass.c1, myCaseClass.c2, myCaseClass.c3)).
agg(typedSum[MyCaseClass](_.c4).name("sum(c4)")).
as[AnotherClass] //this is breaking with exception
</code></pre>
<p>but this again fails with an exception as grouped by key result is not directly mapped with AnotherClass.</p>
<p>PS : any other solution to achieve above is more than welcome.</p>
| <p>The first problem can be resolved by using typed columns all the way down (<code>KeyValueGroupedDataset.agg</code> expects <code>TypedColumn(-s)</code>)
You can defined aggregation result as:</p>
<pre class="lang-scala prettyprint-override"><code>val eight = lit(8.0)
.as[Double] // Not necessary
val sumByEight = typedSum[MyClass](_.c4)
.divide(eight)
.as[Double] // Required
.name("div(sum(c4), 8)")
</code></pre>
<p>and plug it into following code:</p>
<pre class="lang-scala prettyprint-override"><code>val myCaseClass = Seq(
MyClass("a", "b", "c", 2.0),
MyClass("a", "b", "c", 3.0)
).toDS
myCaseClass
.groupByKey(myCaseClass => (myCaseClass.c1, myCaseClass.c2, myCaseClass.c3))
.agg(sumByEight)
</code></pre>
<p>to get</p>
<pre class="lang-none prettyprint-override"><code>+-------+---------------+
| key|div(sum(c4), 8)|
+-------+---------------+
|[a,b,c]| 0.625|
+-------+---------------+
</code></pre>
<p>The second problem is a result of using a class which doesn't conform to a data shape. A correct representation could be:</p>
<pre class="lang-scala prettyprint-override"><code>case class AnotherClass(key: (String, String, String), sum: Double)
</code></pre>
<p>which used with data defined above:</p>
<pre class="lang-scala prettyprint-override"><code> myCaseClass
.groupByKey(myCaseClass => (myCaseClass.c1, myCaseClass.c2, myCaseClass.c3))
.agg(typedSum[MyClass](_.c4).name("sum"))
.as[AnotherClass]
</code></pre>
<p>would give:</p>
<pre><code>+-------+---+
| key|sum|
+-------+---+
|[a,b,c]|5.0|
+-------+---+
</code></pre>
<p>but <code>.as[AnotherClass]</code> is not necessary here if <code>Dataset[((String, String, String), Double)]</code> is acceptable.</p>
<p>You can of course skip all of that and just <code>mapGroups</code> (although not without performance penalty):</p>
<pre class="lang-scala prettyprint-override"><code>import shapeless.syntax.std.tuple._ // A little bit of shapeless
val tuples = myCaseClass
.groupByKey(myCaseClass => (myCaseClass.c1, myCaseClass.c2, myCaseClass.c3))
.mapGroups((group, iter) => group :+ iter.map(_.c4).sum)
</code></pre>
<p>with result</p>
<pre><code>+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
| a| b| c|5.0|
+---+---+---+---+
</code></pre>
<p><code>reduceGroups</code> could be a better option:</p>
<pre><code>myCaseClass
.groupByKey(myCaseClass => (myCaseClass.c1, myCaseClass.c2, myCaseClass.c3))
.reduceGroups((x, y) => x.copy(c4=x.c4 + y.c4))
</code></pre>
<p>with resulting <code>Dataset</code>:</p>
<pre><code>+-------+-----------+
| _1| _2|
+-------+-----------+
|[a,b,c]|[a,b,c,5.0]|
+-------+-----------+
</code></pre>
|
tkinter won't quit when I press quit button, it just changes location <p>This is the code and when I run it the quit button doesn't work:</p>
<pre class="lang-py prettyprint-override"><code>def quit2():
menu.destroy()
def menu1():
menu=Tk()
global menu
play=Button(menu, text='play', command =main)
play.pack()
quit1=Button(menu, text='quit', command=quit2)
quit1.pack()
menu.mainloop()
while True:
menu1()
</code></pre>
| <p>You use <code>while True</code> so after you close window <code>while True</code> opens new window.</p>
<p>Use last line <code>menu1()</code> without <code>while True</code></p>
<p><strong>EDIT:</strong></p>
<pre><code>from tkinter import *
def quit2():
menu.destroy()
def menu1():
global menu
menu = Tk()
play = Button(menu, text='play', command=main)
play.pack()
quit1 = Button(menu, text='quit', command=quit2)
quit1.pack()
menu.mainloop()
#without `while True`
menu1()
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.