text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to mock getWcmMode() using mockito In AEM, there is a Java USE class wherein following code is present getWcmMode().isEdit()
Now, I am struggling to mock this object using mockito in Test java class. Is there any way we can do that?
A: getWcmMode() is a final method in WCMUsePojo, mockito does not support mocking final methods by default.
you will have to enable it by creating a file named org.mockito.plugins.MockMaker in classpath (put it in the test resources/mockito-extensions folder) and put the following single line
mock-maker-inline
then you can use when to specify function return values as usual-
@Test
public void testSomeComponetnInNOTEDITMode() {
//setup wcmmode
SightlyWCMMode fakeDisabledMode = mock(SightlyWCMMode.class);
when(fakeDisabledMode.isEdit()).thenReturn(false);
//ComponentUseClass extends WCMUsePojo
ComponentUseClass fakeComponent = mock(ComponentUseClass.class);
when(fakeComponent.getWcmMode()).thenReturn(fakeDisabledMode);
assertFalse(fakeComponent.getWcmMode().isEdit());
//do some more not Edit mode testing on fakeComponent.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46719848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Url parameter read twice so language service cant pick Updated
I am working on angular5 application where I need to take some data from URL query string.
I am able to get the data but somehow I am getting undefined value which is converted into my expected value later. I want to use this data from query string to decided what language is to be used.
Translate service is working fine if I hardcode .The code is working fine if I hardcode the value in translate.use('en'); I want to assign this value by reading from query string
So basically I want translate.use(this.id) (this.id from url to be passed from query string).
app.component
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<div>
<h2>{{ 'HOME.TITLE' | translate }}</h2>
<label>
{{ 'HOME.SELECT' | translate }}
</label>
</div>
`,
})
export class AppComponent {
id: string;
constructor(public translate: TranslateService,private route: ActivatedRoute) {
translate.addLangs(['en', 'fr']);
translate.setDefaultLang('en');
//const browserLang = translate.getBrowserLang();
//translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
const browserLang = translate.getBrowserLang();
translate.use('en');
}
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log(params);
this.id = params['id'];
})
}
}
Calling way- http://localhost:4200/?id=en or http://localhost:4200/?id=fr
app.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import { RouterModule, Routes } from '@angular/router'
// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,RouterModule.forRoot([]),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I also have i18n folder with json translations.
The code is working fine if I hardcode the value in translate.use('en');
I want to assign this value by reading from query string
So basically I want translate.use(this.id) (this.id from url to be passed from query string).
A: Angular does not use ? in routing, instead it uses ; for multiple parameters
The optional route parameters are not separated by "?" and "&" as they
would be in the URL query string. They are separated by semicolons ";"
This is matrix URL notationβsomething you may not have seen before.
In your case, you are passing a single parameter. So Your route should be similar to
{path: ':param1' component: AppComponent}
Then you would be able to access the param1 using the code written in ngOnInit method. The code should be as shown below
ngOnInit() {
this.activatedRoute.params.subscribe(params=>console.log(params['param1']));
}
If you are planning to use query parameters, then you should use queryParams from ActivateRoute and url should be http://localhost:4216/?param1=en and use below code to access data
ngOnInit(){
this.activatedRoute.queryParams.subscribe(params=>console.log(params['param1']));
}
Also including a working example
A: It was a silly mistake.
Th code was fine but What I was doing was using ng onit to get data from purl string and constructor to inject translation service and was trying to exchange data between thhose two .Since I could not get any way/getting error ,I added both in constructor and removed onit for getting url parameter(I know Silly!)
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import { ActivatedRoute } from '@angular/router';
import { AppGlobals } from '../app/app.global';;
@Component({
selector: 'app-root',
template: `
<div>
<h2>{{ 'HOME.TITLE' | translate }}</h2>
<label>
{{ 'HOME.SELECT' | translate }}
</label>
</div>
`,
providers: [ AppGlobals]
})
export class AppComponent {
param1: string;
constructor(public translate: TranslateService,private route: ActivatedRoute,private _global: AppGlobals) {
console.log('Called Constructor');
this.route.queryParams.subscribe(params => {
this.param1 = params['param1'];
translate.use(this.param1);
});
// this.route.queryParams.subscribe(params => {
// this._global.id = params['id'];
//console.log('hello'+this._global.id);
//})
//translate.addLangs(['en', 'fr']);
//translate.setDefaultLang('en');
//const browserLang = translate.getBrowserLang();
//translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
//const browserLang = translate.getBrowserLang();
console.log('hello'+this._global.id);
translate.use(this._global.id);
}
ngOnInit() {
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50834611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FragmentManager has been destroyed EDIT: It seems that this only happens if my previous activity is in landscape, and the setRequestedOrientation() is portrait, what could possibly be the problem?
I have a code in an activity, which starts a Volley request to a REST API to retrieve some data, and have a callback which will start a fragment if the data was successfully retrieved. However this only works in portrait mode, in landscape mode, it will throw exception with "Fragment Manager Has Been Destroyed".
I can't seem to find the root of this problem, therefore I can't try any alternative solutions.
This is my onCreate() method of this activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(SettingsManager.getOrientationSettings(this));
setContentView(R.layout.activity_settings);
findViews();
setListeners();
getSettings();
}
goSettings() will retrieve the data, set requested orientation will either be ActivityInfo.SCREEN_ORIENTATION_PORTRAIT or ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE.
My loadFirstPage() method:
private void loadFirstPage() {
VMSSettingsPageOneFragment fragment = new VMSSettingsPageOneFragment();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.settings_fragment_container, fragment)
.commit();
}
The error message:
E/FileUtils: File Write Exception
java.lang.IllegalStateException: FragmentManager has been destroyed
at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1853)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:321)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:286)
at com.timeteccloud.icomm.platformVMS.settingsActivity.VMSSettingsActivity.loadFirstPage(VMSSettingsActivity.java:87)
A: You can implement a check before committing the fragment transaction, something as follows.
public boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.main_frame_layout, fragment);
if (!fm.isDestroyed())
transaction.commit();
return true;
}
return false;
}
A: maybe you can use parentFragmentManager.beginTransaction() instead of childFragmentManager in code will look like
dialog.show(parentFragmentManager.beginTransaction(), BaseFragment.TAG_DIALOG)
A: Hi you can just use it like this way
declare a handler
Handler handler = new Handler()
and Then put commit in to post delayed of handler
// this is a hack to fix fragment has been destroyed issue do not put Transaction.replace
// into handler post delayed
handler.postDelayed({
// transaction.addToBackStack(null)
transaction.commit()
},500)
Do not place other things in post delayed ie. adding fragment to transaction (or replace transaction.replace(fragment,containerid,tag))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58814735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: for each not updating variables When using the AS3 for each construct I find that I can't update the members of the array that im iterating.
for each( obj:Object in array ){
obj = new Object();
}
when I loop over the array again they will still have the same values as before the loop.
Am I stuck with using tradition for-loops in this situation or is there a way to make the updates stick.
A: As Daniel indicated, you are instantiating a new object to the obj reference instead of the array element. Instead, access the array by ordinal:
var array:Array = [{}, {}, {}];
for (var i:uint = 0; i < array.length; i++)
{
array[i] = {};
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17073211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: play video in app through video out http://www.google.com/products/catalog?oe=UTF-8&gfns=1&q=iphone+video+out+cable&um=1&ie=UTF-8&cid=17045329161497634089&ei=JpU1TcymOcnogQfC25C7Cw&sa=X&oi=product_catalog_result&ct=result&resnum=5&ved=0CCgQ8wIwBA#
I want to know if its possible to play video from an app through a lead like this onto a TV or something similar. I've heard that the functionality is not available in apps. Is this true?
If its not true and its perfectly possible what exactly is possible? Is it possible to push a different video output to the external TV as that that is on the device?
Thanks
Tom
A: I suppose that cable will have the same functionality as a connector for a projector or second display right?
If that is the case then the answer is: IS POSSIBLE.
But, everything that is want to show in the second display have to be explicitly done by you. There is no mirroring system or something alike.
Read here, there is a sample app also :)
http://mattgemmell.com/2010/06/01/ipad-vga-output
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4724600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to aggregate timestamp data in Spark to smaller time frame I'm working on a project using New York taxi data. The data contain records for pickup location (PULocationID), and the timestamp (tpep_pickup_datetime) for that particular pick-up record.
I want to aggregate the data to be hourly for each location. The aggregation should have an hourly count of pick-ups per location.
A: The information you provided is a bit lacking. From what I understood, these could be possible aggregation options.
Using date_trunc
from pyspark.sql import functions as F
df = df.groupBy(
F.date_trunc('hour', 'tpep_pickup_datetime').alias('hour'),
'PULocationID',
).count()
df.show()
# +-------------------+------------+-----+
# | hour|PULocationID|count|
# +-------------------+------------+-----+
# |2020-01-01 00:00:00| 238| 1|
# |2020-01-01 02:00:00| 238| 2|
# |2020-01-01 02:00:00| 193| 1|
# |2020-01-01 01:00:00| 238| 2|
# |2020-01-01 00:00:00| 7| 1|
# +-------------------+------------+-----+
Using window
from pyspark.sql import functions as F
df = df.groupBy(
F.window('tpep_pickup_datetime', '1 hour').alias('hour'),
'PULocationID',
).count()
df.show(truncate=0)
# +------------------------------------------+------------+-----+
# |hour |PULocationID|count|
# +------------------------------------------+------------+-----+
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|238 |2 |
# |[2020-01-01 01:00:00, 2020-01-01 02:00:00]|238 |2 |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|238 |1 |
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|193 |1 |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|7 |1 |
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72827699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Declaring a global CSS variable generates error in Dreamweaver As found here I am trying to declare a golbal CSS variable in a root element. The html displays correctly and I cannot find any error except the one Dreamweaver tells me:
*
*"Expected RBRACE at line 5, col 3"
*"Expected RBRACE at line 6, col 3"
*...
It seems as I could ignore DW here, but it leaves a bad feeling in my gut. Am I missing something obvious, or is DW wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69884165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to form a correct MySQL connection string? I am using C# and I am trying to connect to the MySQL database hosted by 00webhost.
I am getting an error on the line connection.Open():
there is no MySQL host with these parameters.
I have checked and everything seems to be okay.
string MyConString = "SERVER=mysql7.000webhost.com;" +
"DATABASE=a455555_test;" +
"UID=a455555_me;" +
"PASSWORD=something;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "INSERT Test SET lat=" +
OSGconv.deciLat + ",long=" + OSGconv.deciLon;
connection.Open();
Reader = command.ExecuteReader();
connection.Close();
What is incorrect with this connection string?
A: string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
A: Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
A: try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10505952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Installing SSL On apache2 & Ubuntu 14.04 I'm trying to install ssl on my apache2.4.7 ubuntu 14.04 server
I'm following the digital ocean tutorial here
but it keeps redirecting me to the normal http version. This is my 000-default.conf in sites-available (even when I delete the whole content it still loads my website)
<VirtualHost *:443>
ServerName xxxxxx.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/xxxxxx.com.crt
SSLCertificateKeyFile /etc/apache2/ssl/xxxxxx.com.key
SSLCertificateChainFile/etc/apache2/ssl/intermediate.crt
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
A: Looks like you have a process running on the 443 port so when apache tries to get on that, it fails.
netstat -tlpn | grep 443
use that to find out which process is using it. It should give you process id as well.
service <process> stop
or
kill <processID> to kill the process that is using your 443 port. Clear your apache logs and restart apache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32218634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sql injection mysql_real_escape_string I have a dilemma how should I mysql_real_escape_string() my variables without inserting them into the database \n, \r, \x00 when someone uses " ' or <br> on my comment field, I tried with preg_replace instead of mysql_real_escape_string, but seems I don't know exactly how to allow all the chars and signs I want.
A: mysql_real_escape_string only escapes values so that your queries don't break, it also protects against SQL injection if used correctly.
If you don't want certain characters you will need to use additional functions to strip them before you apply mysql_real_escape_string.
[insert obligatory "use prepared statements" comment]
Ex:
$string = "My name is
John";
$filtered_string = str_replace("\n", " ", $string); // filter
$escaped = mysql_real_escape_string($filtered_string); // sql escape
mysql_query("INSERT INTO `messages` SET `message` = '" . $escaped . "'");
A: You should be able to use str_replace to help with this:
mysql_real_escape_string(str_replace(array("\n", "\r\n", "\x00", '"', '\''), '', $input));
Having said that, it is a good idea to switch to mysqli or PDO for database read / write. Both of these allow prepared statements, which reduce the risk of SQL injections.
Here's an example of PDO:
$stmt = $PDOConnection->prepare('INSERT INTO example_table (input_field) VALUES (:input_field)');
$stmt->bindParam(':input_field', $input);
$stmt->execute();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14283556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring MockWebServiceServer handling multiple async requests I have multiple async soap requests and I need to mock the responses of those requests. However, it seems the order of the expected requests matter and I was wondering if there were any workarounds.
I came across this example using MockRestServiceServer where it uses the ignoreExpectOrder() method.
A: You can write your own implementation of the ResponseCreator that sets up a number of URI and responses (for asynchronous requests) and return the matching response based on the input URI. I've done something similar and it is works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52935325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to express the type for a constant? I have to write some functions with a significant amount of constant in it in a relatively small amount of lines.
( Don't bother about the way I wrote the formula, it's there to simply express the fact that I have a lot of constants in a small package, this specific example is small too, in practice I have a minimum of 6-7 constants for each function )
T foo( T x )
{
return k1 * k2 * x - k3;
}
Assuming that I'm not interested in declaring the constants as static ( it will also cause problems with the naming convention in my specific case ) const T k1 = 42; , I would like to find an alternative .
A viable alternative can be
T foo( T x )
{
return uint32_t{42} * uint32_t{21} * x - uint32_t{33};
}
At this point there are 2 main problems:
*
*I'm not sure if this kind of declaration will create an entire object or just "a number"
*it's a C++ only solution and I'm writing really simple functions that should be C99+ compatible .
Why I would like to do this ?
It's simple, the values for this constants are highly variable, really small values or big values, with really small values there is a significant amount of space wasted, plus this constants are math constants so they will never change and I can optimize this section right from the first release.
There is also another aspect, the default type for numeric constants is a signed integer, I would like to go for an unsigned integer type of arbitrary size.
The problem with the static declaration const T k1 = 42; outside the functions, is that different constants have the same name, the value of the constant is different because the function is different, but the name of the constant, mathematically speaking, is the same, so with this solution I'll end up having multiple declarations of the same variable in the same scope. That's why I can't use names or this kind of declarations .
Do you have any idea for writing this in a way that is compatible with both C++ and C ?
A: In C, for integers, you add 'U', 'L', or 'LL' to numbers to make them unsigned, long, or long long in a few combinations
a = -1LL; // long long
b = -1U; // unsigned
c = -1ULL; // unsigned long long
d = -1LLU; // unsigned long long
e = -1LU; // unsigned long
f = -1UL; // unsigned long
One other option, in C, is to cast. The compiler, very probably, will do the right thing :)
return (uint32)42 - (int64)10;
But probably the best option, as pointed by ouah in the comments below, is to use Macros for integer constants (C99 Standard 7.18.4)
a = UINT32_C(-1); // -1 of type uint_least32_t
b = INT64_C(42); // 42 of type int_least64_t
A: Is there something wrong this?
inline T foo(T x)
{
int k1 = 42;
int k2 = 21;
int k3 = 33;
return 1ull * x * k1 * k2 - k3;
}
Your comments on the other answer suggest you are unsure about which types to use for the constants.
I don't see what the problem is with just using any type in which that constant is representable.
For the calculation expression, you would need to think about the size and signed-ness of intermediate calculations. In this example I start with 1ull to use unsigned arithmetic mod 2^64. If you actually wanted arithmetic mod 2^32 then use 1ul instead, and so on.
Can you elaborate on what you meant by "space wasted"? It sounds as if you think there is some problem with using 64-bit ints. What sort of "space" are you talking about?
Also, to clarify, the reason you don't want to declare k1 global is because k1 has a different value in one function than it does in another function? (As opposed to it having the same value but you think it should have a different data type for some reason).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23660950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to allow your app with usage access? From android lollipop, the app that wants to access usage of other apps needs to be enabled by security. Rather than manually enabling it manually by Settings -> Security -> Apps with usage access, I want to enable it programmatically. I cannot find a clear answer anywhere. Can anyone help me on this one?
A: Try this in your activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isAccessGranted()) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
}
private boolean isAccessGranted() {
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
A: try this code i hope help you
if (Build.VERSION.SDK_INT >= 21) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats == null || stats.isEmpty()) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);
context.startActivity(intent);
}
}
A: Add this permission in your manifest
uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
and continue with this answer
https://stackoverflow.com/a/39278489/16126283
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38573857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I create a list of dates, before doing a LEFT JOIN? I am using BigQuery SQL. I have the following tables:
Table "public.org" (records all organisations)
Column β Type β Modifiers
βββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββ
code β character varying(6) β not null
name β character varying(200) β not null
setting β integer β not null
Table "public.spending" (records spending on chemical by org by month)
Column β Type β Modifiers
ββββββββββββββββββββΌββββββββββββββββββββββββββΌβββββββββββ
org_id β character varying(6) β not null
month β date β not null
chemical_id β character varying(9) β not null
actual_cost β double precision β not null
And I want to calculate the spending on a particular chemical by month, by organisation. The complication is if there was no spending by an organisation on that chemical in a month, there is simply no entry in the spending table, rather than a zero entry. However, I would like output (a null or zero result, I don't mind which).
Right now I have this, which gives me total spending for all organisations including those that had no entries, but does not separate spending out by month:
SELECT
org.code AS code,
org.name AS name,
num.actual_cost as actual_cost
FROM (
SELECT
code,
name
FROM
org
WHERE
setting=4) AS orgs
LEFT OUTER JOIN EACH (
SELECT
org_id,
SUM(actual_cost) AS actual_cost
FROM
spending
WHERE
chemical_id='1202010U0AAAAAA'
GROUP BY
org_id) AS num
ON
num.org_id = orgs.code
So now I need to extend it to do a LEFT JOIN by month and organisation. I know that I can get the unique months in the spending table by doing this:
SELECT month FROM spending GROUP BY month
(NB BigQuery doesn't support UNIQUE.)
But how do I get all the unique rows for month and organisation, and only then do a LEFT JOIN onto the spending?
A: If we are talking about calendar months there we have only 12 options (Jan => Dec).
Just compile a static table or in the query itself as 12 selects that form a table, and use that to join.
select * from
(select 1 as m),
(select 2 as m),
....
(select 12 as m)
you might also be interested in the Technics mentioned in other posts :
*
*How to extract unique days between two timestamps in BigQuery?
*Hits per day in Google Big Query
A: I'm not sure if this works in bigquery, but this is the structure of a query that does what you want:
select org.name, org.code, m.month, sum(s.actual_cost)
from org cross join
(select month from public.spending group by month) m left join
pubic.spending s
on s.ord_ig = org.code and s.month = m.month
where prescribing_setting = 4
group by org.name, org.code, m.month;
A: I would suggested following steps for you to get through:
STEP 1 - identify months range (start and finish)
month is assumed to be presented in format YYYY-MM-01
if it is in different format - code should be slightly adjusted
SELECT
MIN(month) as start,
MAX(month) as finish
FROM public.spending
Assume Result of Step 1 is
'2014-10-01' as start, '2015-05-01' as finish
Step 2 - produce all months in between Start and Finish
SELECT DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, "MONTH")) AS month
FROM (
SELECT ROW_NUMBER() OVER() AS pos, * FROM (FLATTEN((
SELECT SPLIT(RPAD('', 1000, '.'),'') AS h FROM (SELECT NULL)),h
))) nums
CROSS JOIN (
SELECT '2014-10-01' AS start, '2015-05-01' AS finish // <<-- Replace with SELECT from Step 1
) range
WHERE pos BETWEEN 1 AND 1000
AND DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, "MONTH"))
BETWEEN start AND finish
So, now - Result of Step 2 is
month
2014-10-01
2014-11-01
2014-12-01
2015-01-01
2015-02-01
2015-03-01
2015-04-01
2015-05-01
It has all months, even if some are missed in public.spending table in between start and finish
I think the rest is trivial and you have already main code for it.
Let me know if this is not accurate and you need help in completing above steps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34179398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Class to test if date is valid using Int input with boolean output, and how to test (java) I have an assignment for class in which I have to create a class (called FunWithCalendars) that takes in 3 int values (month, day, and year) and uses 1 boolean method (isValid) to check if the overall date is valid, which uses 3 other helper methods (isLeapYear, isValidMonth, isValidDay) to determine whether the day and month given are valid. I now want to test my file in Eclipse.
So far I've learned to test classes/methods with this code ( Im a newbie, so this is the only way I know):
public class driverFunWithCalendars {
public static void main(String [] args ) {
FunWithCalendars test = new FunWithCalendars () ;
System.out.println( test.FunWithCalendars () );
However, Im not understanding how I'm supposed to test the boolean method for a true or false when I have to enter int values that aren't defined in the method. The error in the code above is at "new FunWithCalendars () ;" and "(test.funwithcalendars () );".
Here's my main code:
public class FunWithCalendars
{
private int month, day, year;
public FunWithCalendars( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
public boolean isValid ( boolean isValidMonth, boolean isValidDay )
{
if ( isValidMonth && isValidDay )
{
return true;
}
else
{
return false;
}
}
public boolean isLeapYear (int year)
{
if ( (year / 400) == 0 )
{
return true;
}
else if ( ((year / 4) == 0) && ((year/100) !=0))
{
return true;
}
else
{
return false;
}
}
public boolean isValidMonth ( int month )
{
if ( month >= 1 && month <= 12 )
{
return true;
}
else
{
return false;
}
}
public boolean isValidDay ( int month, int day, int year, boolean isLeapYear )
{
if ( (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && ((day<=31) && (day>=1)) )
{
return true;
}
else if ( (month == 4 || month == 6 || month == 9 || month == 11) && ((day<=30) && (day>=1)) )
{
return true;
}
else if ( (month == 2) && ( isLeapYear = true) && ((day<=29) && (day>=1)) )
{
return true;
}
else if ( (month == 2) && ( isLeapYear = false) && ((day<=28) && (day>=1)) )
{
return true;
}
else
{
return false;
}
}
}
}
}
Basically, I just want to know how I can test my code with 3 int values ( a date, or month, day year) to see if the date is valid or not using my isValid method. I'm really sorry if my question is unclear, or the assignment in the way I explained is confusing but like I said Im a newbie to Java and to Stackoverflow questions and I have yet to understand Java to the point that I can ask more efficient and concise questions, but I really hope some of you can help me. Ill also attach a transript of my original assignment, which may be less confusing and helpful to you if you're trying to help me:
/*
The calendar we use today is the Gregorian Calendar, devised by Italian astronomer Aloysius Lilius and decreed by Pope Gregory XIII on February 24th, 1582. In the Gregorian Calendar, the average length of a year is exactly 365.2425 days. We can make that happen with some rather complex "leap year" rules:
If a year is divisible by 4, it's a leap year⦠unless it's divisible by 100, in which case it's not a leap year⦠unless it's divisible by 400, in which case it's a leap year.
Okay, that's confusing. Let's try again:
A year is a leap year if:
a. It's divisible by 400
b. It's divisible by 4 and it's not divisible by 100.
Based on those rules, 1512, 1600, and 2000 were leap years. 1514, 1700, and 1900 were not.
(And you thought leap year was just every four years! That was the case with Julius Caesar's calendarβwhich was wrong, because adding a 366th day every four years would give us an average year length of 365.25 days instead of the far more accurate 365.2425 days. 0.0075 days per year doesn't sound like a lot, but in the 1500s astronomers noticed that predictable events, such as the solstice and equinox, were "off" by about 10 days. Hence the new, improved calendar.)
In the Gregorian Calendar, the number of days per month are as follows:
Month Name Days
1 January 31
2 February 28 or 29
3 March 31
4 April 30
5 May 31
6 June 30
7 July 31
8 August 31
9 September 30
10 October 31
11 November 30
12 December 31
Based on the Gregorian Calendar's leap year rules, and the usual number of days per month, complete the class FunWithCalendars. You will need:
Three int field variables to keep track of the month, day, and year.
The constructor of FunWithCalendars, which will take in values for the month, day, and year, and assign them to field variables. (This is written for you, you may use the starter file FunWithCalendars.java ).
The method:
boolean isValid()
which will return a true or false. A true result means that the month and day are valid values for that year.
You will need three helper methods:
boolean isLeapYear()
which will return a true only if the year represents a leap year.
You also need:
boolean isValidMonth()
which will return a true only if the month field is between 1 and 12. And finally:
boolean isValidDay()
which will return a true only if that day exists in that month in the given year. Remember to check for a leap year when checking to see if 29 is valid in February!
Again, we expect a true from isValid() if and only if we get a true from isValidMonth() and from isValidDay(). (We will assume that all years are valid.)
Tests:
7/20/2010 is valid.
13/1/2009 is not valid. (13 is not a valid month.)
11/31/2009 is not valid. (That day does not exist in that month.)
2/29/2007 is not valid. (2007 was not a leap year.)
2/29/2000 is valid. (2000 was a leap year.)
*/
Thanks to anyone who can help!
A: Letβs take the first test as an example:
Tests:
7/20/2010 is valid.
So in your driver class/test class construct a FunWithCalendars object denoting July 20 2010. The constructor takes three arguments for this purpose. Next call its isValid method. I believe that the idea was that you shouldnβt need to pass the same arguments again. Your isValid method takes two boolean arguments. Instead I believe that it should take no arguments and itself call the two helper methods passing the values that are already inside the FunWithCalendars object. So before you can get your driver class to work, I believe you have to fix your design on this point.
Once you get the call to isValid() to work, store the return value into a variable. Compare it to the expected value (true in this case). If they are equal, print a statement that the test passed. If they are not equal, print a statement containing both the expected and the observed value.
Do similarly for the other tests. Donβt copy-paste the code, though. Instead wrap it in a method and call the method for each test case, passing as arguments the data needed for that particular test. Remember to include the expected result as an argument so the method can compare.
Edit:
β¦ My confusion is in how to construct an object (in general, and also
specifically FunWithCalendars), how to call the isValid method and
have it not take any arguments, how to have the isValid method call
the two helper methods which pass the values that are in the
FunWIthCalendars object.
Itβs basic stuff, and I donβt think Stack Overflow is a good place to teach basic stuff. Letβs give it a try, only please set your expectations low.
How to construct an object: Youβre already doing this in your driver class using the new operator:
FunWithCalendars test = new FunWithCalendars () ;
Only you need to pass the correct arguments to the constructor. Your constructor takes three int arguments, so it needs to be something like:
FunWithCalendars test = new FunWithCalendars(7, 20, 2020);
How to call the isValid method and have it take no arguments, after the above line:
boolean calculatedValidity = test.isValid();
This stores the value returned from isValid() (false or true) into a newly created boolean variable that I have named calculatedValidity. From there we may check whether it has the expected value, act depending on it and/or print it. The simplest thing is to print it, for example:
System.out.println("Is 7/20/2020 valid? " + calculatedValidity);
Calling with no arguments requires that the method hasnβt got any parameters:
public boolean isValid ()
{
How to have isValid() call the two helper methods: You may simple write the method calls en lieu of mentioning the parameters that were there before. Again remember to pass the right arguments:
if (isValidMonth(month) && isValidDay(month, day, year, isLeapYear(year)) )
In the method calls here I am using the instance variables (fields) of the FunWithCalendars object as arguments. This causes the method to use the numbers that we entered through the constructor and to use the three helper methods.
I have run your code with the above changes. My print statement printed the expected:
Is 7/20/2020 valid? true
PS I am on purpose not saying anything about possible bugs in your code. Itβs a lot better for you to have your tests tell you whether there are any.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64423047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to upload multiple files using Django I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light .
I have created my html form like this
<input type="file" name="file" multiple />
I have created a model like this
class Report(models.Model):
name = models.CharField(max_length=60)
report = models.CharField(max_length=10)
task = models.CharField(max_length=60)
date = models.DateField(null=True)
start_time = models.TimeField()
end_time = models.TimeField()
no_of_hours = models.CharField(max_length=20)
team_lead = models.CharField(max_length=30)
today_progress = models.CharField(max_length = 1000)
file_input = models.FileField(upload_to='documents/')
concern = models.CharField(max_length=1000)
next_plan = models.CharField(max_length=1000)
next_plan_file = models.FileField(upload_to='next/')
And views.py like this
def save(request):
report_object = Report()
report_object.name = request.POST["name"]
report_object.report = request.POST["report"]
report_object.task = request.POST["task"]
report_object.date = request.POST["date"]
report_object.start_time = request.POST["start_time"]
report_object.end_time = request.POST["end_time"]
report_object.no_of_hours = request.POST["no_of_hours"]
report_object.team_lead = request.POST["team_lead"]
report_object.today_progress = request.POST["today_progress"]
report_object.file_input = request.FILES.["file_input"]
report_object.concern = request.POST["concern"]
report_object.next_plan = request.POST["next_plan"]
report_object.next_plan_file = request.FILES.["upload_next"]
report_object.save()
return redirect('/')
I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel
Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ?
And even want to show in Django Admin Panel
A: Try this and check out this works!!
Replace
file=request.FILES.get('file')
with
files = request.FILES.getlist('file')
you have to loop through each element in your view
if form.is_valid():
name = form.cleaned_data['name']
for f in files:
File.objects.create(name=name, file=f)
return HttpResponse('OK')
Here name is your model field and saving all uploaded files in name field
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62132613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Working with images in C++ or C The first thing is that I am a beginner. Okay?
I've read related answers and questions, but please help me with this problem:
How can I open an JPEG image file in C++, convert it to a grayscale image, get its histogram, resize it to a smaller image, crop a particular area of it, or show a particular area of it?
For these tasks, is C or C++ faster in general?
What libraries are simplest and fastest? The running time is very important.
Thanks.
A: There are many good libraries for working with images in C and C++, none of which is clearly superior to all others. OpenCVwiki, project page has great support for some of these tasks, while ImageMagickwiki, project page is good at others. The JPEG group has its own implementation of JPEG processing functions as well. These are probably good resources to start from; the API documentation can guide you more specifically on how to use each of these.
As for whether C or C++ libraries are bound to be faster, there's no clear winner between the two. After all, you can always compile a C library in C++. That said, C++ libraries tend to be a bit trickier to pick up because of the language complexity, but much easier to use once you've gotten a good feel for the language. (I am a bit biased toward C++, so be sure to consider the source). I'd recommend going with whatever language you find easier for the task; neither is a bad choice here, especially if performance is important.
Best of luck with your project!
A: well for basic image manipulations you could also try Qt's QImage class (and other). This gives you basic functionality for opening, scaling, resizing, cropping, pixel manipulations and other tasks.
Otherwise you could as already said use ImageMagick or OpenCV. OpenCV provides a lot of examples with it for many image manipulation/image recognition tasks...
Hope it helps...
A: here is an example using magick library.
program which reads an image, crops it, and writes it to a new file (the exception handling is optional but strongly recommended):
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
// Construct the image object. Seperating image construction from the
// the read operation ensures that a failure to read the image file
// doesn't render the image object useless.
Image image;
try {
// Read a file into image object
image.read( "girl.jpeg" );
// Crop the image to specified size (width, height, xOffset, yOffset)
image.crop( Geometry(100,100, 100, 100) );
// Write the image to a file
image.write( "x.jpeg" );
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
return 0;
}
check many more examples here
A: libgd is about the easiest, lightest-weight solution.
gdImageCreateFromJpeg
gdImageCopyMergeGray
gdImageCopyResized
Oh, and it's all C.
A: If running time is really important thing then you must consider image processing library which offloads processing job to GPU chip, such as:
*
*Core Image (Osx)
*OpenVIDIA (Windows)
*GpuCV (Windows, Linux)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4906736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android: Disable texture filtering/interpolation on AnimationDrawable I have a frame-by-frame AnimationDrawable that I'd like to scale without Android's default, blurry interpolation. (It's pixel art and looks better with nearest-neighbor.) Can I set a flag? Override onDraw? Anything to tell the GPU not to use texture filtering?
Do I need to scale up each individual bitmap in the animation instead? This seems like a waste of CPU and texture memory.
Code example:
// Use a view background to display the animation.
View animatedView = new View(this);
animatedView.setBackgroundResource(R.anim.pixel_animation);
AnimationDrawable animation = (AnimationDrawable)animatedView.getBackground();
animation.start();
// Use LayoutParams to scale the animation 4x.
final int SCALE_FACTOR = 4;
int width = animation.getIntrinsicWidth() * SCALE_FACTOR;
int height = animation.getIntrinsicHeight() * SCALE_FACTOR;
container.addView(animatedView, width, height);
A: This seems to work, as long as you can assume that all the frames in an AnimationDrawable are BitmapDrawables:
for(int i = 0; i < animation.getNumberOfFrames(); i++) {
Drawable frame = animation.getFrame(i);
if(frame instanceof BitmapDrawable) {
BitmapDrawable frameBitmap = (BitmapDrawable)frame;
frameBitmap.getPaint().setFilterBitmap(false);
}
}
A: If you know the texture ID of the texture that's being rendered, at any time after it's created and before it's rendered you should be able to do:
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
If this is the only texture being rendered then you can do that anywhere from your render thread and it will get picked up without having to explicitly glBindTexture().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23750139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use the pumping lemma to show that the following languages are not regular languages L = {anbm | n = 2m} Use the pumping lemma to show that the following languages are not regular languages L = {an bm | n = 2m}
A: Choose a string a^2p b^p. The pumping lemma says we can write this as w = uvx such that |uv| <= p, |v| < 0 and for all natural numbers n, u(v^n)x is also a string in the language. Because |uv| <= p, the substring uv of w consists entirely of instances of the symbol a. Pumping up or down by choosing a value for n other than one guarantees that the number of a's in the resulting string will change, while the number of b's stays the same. Since the number of a's is twice the number of b's only when n = 1, this is a contradiction. Therefore, the language cannot be regular.
A: L={anbm|n=2m} Assume that L is regular Language Let the pumping length be p L={a2mbm} Since |s|=3m > m (total string length) take a string s S= aaaaa...aabbb....bbb (a2mbm times taken) Then, u = am-1 ; v= a ; w= ambm. && |uv|<=m Now If i=2 then S= am-1 a2 ambm = a2m-1bm Since here we are getting an extra a in the string S which is no belong to the given language a2mbm our assumption is wrong Therefore it is not a regular Language
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62106698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Declaring constants with the nameof() the constant as the value Scenario
I have a class for declaring string constants used around a program:
public static class StringConstants
{
public const string ConstantA = "ConstantA";
public const string ConstantB = "ConstantB";
// ...
}
Essentially, it doesn't matter what the actual value of the constant is, as it used when assigning and consuming. It is just for checking against.
The constant names will be fairly self-explanatory, but I want to try and avoid using the same string values more than once.
What I would like to do
I know that nameof() is evaluated at compile-time, so it is entirely possible to assign the const string's value to the nameof() a member.
In order to save writing these magic strings out, I have thought about using the nameof() the constant itself.
Like so:
public static class StringConstants
{
public const string ConstantA = nameof(ConstantA);
public const string ConstantB = nameof(ConstantB);
// ...
}
Question...
I guess there is no real benefit of using the nameof(), other than for refactoring?
Are there any implications to using nameof() when assigning constants?
Should I stick to just using a hard-coded string?
A: Whilst I think the use of nameof is clever, I can think of a few scenarios where it might cause you a problem (not all of these might apply to you):
1/ There are some string values for which you can't have the name and value the same. Any string value starting with a number for example can't be used as a name of a constant. So you will have exceptions where you can't use nameof.
2/ Depending how these values are used (for example if they are names of values stored in a database, in an xml file, etc), then you aren't at liberty to change the values - which is fine until you come to refactor. If you want to rename a constant to make it more readable (or correct the previous developer's spelling mistake) then you can't change it if you are using nameof.
3/ For other developers who have to maintain your code, consider which is more readable:
public const string ConstantA = nameof(ContantA);
or
public const string ConstantA = "ConstantA";
Personally I think it is the latter. In my opinion if you go the nameof route then that might give other developers cause to stop and wonder why you did it that way. It is also implying that it is the name of the constant that is important, whereas if your usage scenario is anything like mine then it is the value that is important and the name is for convenience.
If you accept that there are times when you couldn't use nameof, then is there any real benefit in using it at all? I don't see any disadvantages aside from the above. Personally I would advocate sticking to traditional hard coded string constants.
That all said, if your objective is to simply to ensure that you are not using the same string value more than once, then (because this will give you a compiler error if two names are the same) this would be a very effective solution.
A: I think nameof() has 2 advantages over a literal strings:
1.) When the name changes, you will get compiler errors unless you change all occurences. So this is less error-prone.
2.) When quickly trying to understand code you didn't write yourself, you can clearly distinguish which context the name comes from. Example:
ViewModel1.PropertyChanged += OnPropertyChanged; // add the event handler in line 50
...
void OnPropertyChanged(object sender, string propertyName) // event handler in line 600
{
if (propertyName == nameof(ViewModel1.Color))
{
// no need to scroll up to line 50 in order to see
// that we're dealing with ViewModel1's properties
...
}
}
A: Using the nameof() operator with public constant strings is risky. As its name suggests, the value of a public constant should really be constant/permanent. If you have public constant declared with the nameof() and if you rename it later then you may break your client code using the constant. In his book Essential C# 4.0, Mark Michaelis points out: (Emphasis is mine)
public constants should be permanent because changing their value will
not necessarily take effect in the assemblies that use it. If an
assembly references constants from a different assembly, the value of
the constant is compiled directly into the referencing assembly.
Therefore, if the value in the referenced assembly is changed but the
referencing assembly is not recompiled, then the referencing assembly
will still use the original value, not the new value. Values that
could potentially change in the future should be specified as readonly
instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40888699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Magento connect's order delivery date extension disable required dates I used Magento connects Order Delivery Date extension to allow the buyer to set the date, when they should receive the goods. Now i want to disable some dates on the calendar that shows at checkout page. Can i use general JQuery calendar date disable at this point? If i can not what is the way it should be done? Any helps would be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20964588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to obtain list of devices and their parameters using HKLM\SYSTEM\CurrentControlSet\Enum? How to obtain the content and the main parameters of devices using registry section HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum?
Well, I need to scan registry tree, containing ..\Enum\{SomeID}\{OneMoreID}\{MyDearValue}, which should contain some description, i.e. "KINGSTON 100500TB Flash of God". And the main question is: how to obtain all of this string descriptions, using WinAPI and C++?
A: Use the Win32 Registry functions.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724875(v=vs.85).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14426521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Linq to sql table dynamically with ExecuteQuery VB I am using VB Framework 4.0 and Linq to sql.
I want to choose dynamycally the name of table. I have used the library namedtable.dll and I have mapped all the tables of database and it's Ok.
My problem is when I try to execute executequery. Here my code.
Imports Microsoft.VisualBasic
Imports System.Data.Linq
Imports Prototype.NamedTable.Data
Imports Prototype.NamedTable.Utility
Public Class tipos
Private _conexion As String = "conexion"
Public Sub New()
End Sub
...........
Public Function getConsulta(byval tableName as String) As IList(Of TIPOS)
Dim context As New DataContext(_conexion)
sql = " select COD, NAME from " & tableName
Dim a = context.ExecuteQuery(Of TIPOS)(sql)
Return sql.ToList
End Function
End Class
but I have an error: "El tipo 'TIPOS' debe declarar un constructor predeterminado (sin parΓ‘metros) para que pueda construirse durante la asignaciΓ³n." that in English is:
"The type 'Type TIPOS' must declare a default (parameterless) constructor in order to be constructed during mapping"
I have defined "TIPOS" in other file:
Public Interface TIPOS
<Column(CanBeNull:=False)> Property COD Integer
<Column(CanBeNull:=False)> Property NAME As String
End Interface
Public Class ITIPO : Implements TIPO
Private _cod As Integer
Private _name As String
Public Property COD As Integer Implements TIPO.COD
Get
Return _cod
End Get
Set(ByVal value As Integer)
_cod = value
End Set
End Property
Public Property NAME As String Implements TIPO.NAME
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
I need help!
Sorry for my English.
A: The solution can be found on codeproject.com in article "Dynamic Table Mapping for LINQ-to-SQL." Below is a static class you can use. Please see the article for instructions on what you must do to use the 4 different generic methods. Here is an invocation example:
public interface IResult
{
[Column(IsPrimaryKey = true)]
int Id { get; set; }
[Column]
string Name { get; set; }
[Column]
double Value { get; set; }
}
public void TestThis()
{
var connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False";
var context = new DataContext(connectionString);
var table = context.GetTable<IResult>("YourTableName");
var query = from r in table where r.Id == 108 select r;
var list = query.ToList();
}
Class Code:
namespace Prototype.NamedTable
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
/// <summary>
/// The utility.
/// </summary>
public static class Utility
{
#region Constants and Fields
/// <summary>
/// The named types.
/// </summary>
private static readonly Dictionary<string, Type> NamedTypes = new Dictionary<string, Type>();
/// <summary>
/// The _assembly builder.
/// </summary>
private static AssemblyBuilder _assemblyBuilder;
/// <summary>
/// The _module builder.
/// </summary>
private static ModuleBuilder _moduleBuilder;
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether Verbose.
/// </summary>
public static bool Verbose { get; set; }
#endregion
#region Public Methods
/// <summary>
/// The clear.
/// </summary>
public static void Clear()
{
_assemblyBuilder = null;
NamedTypes.Clear();
}
/// <summary>
/// Retrieve a table from the data context which implements ITable<TEntity> by T and use ITable<TBack>
/// </summary>
/// <typeparam name="TEntity">
/// Entity Type
/// </typeparam>
/// <typeparam name="TBack">
/// Backing Type
/// </typeparam>
/// <param name="context">
/// Data Context
/// </param>
/// <returns>
/// </returns>
public static ATable<TEntity> GetTable<TEntity, TBack>(this DataContext context) where TEntity : class
where TBack : class
{
// Create the backup table
Table<TBack> refer = context.GetTable<TBack>();
// Prepare the cloning method
Delegate cloneFrom = CompileCloning(typeof(TEntity), typeof(TBack));
// Construct the table wrapper
return new ATable<TEntity>(refer, cloneFrom);
}
/// <summary>
/// Retrieve a table from the data context which implements ITable<TEntity> uses specific backing table
/// </summary>
/// <typeparam name="TEntity">
/// Entity Type
/// </typeparam>
/// <param name="context">
/// Data context
/// </param>
/// <param name="name">
/// Table name
/// </param>
/// <returns>
/// </returns>
public static ATable<TEntity> GetTable<TEntity>(this DataContext context, string name) where TEntity : class
{
// Create/Retrieve a type definition for the table using the TEntity type
Type type = DefineEntityType(typeof(TEntity), name);
// Create the backup table using the new type
ITable refer = context.GetTable(type);
// Prepare the cloning method
Delegate cloneFrom = CompileCloning(typeof(TEntity), type);
// Construct the table wrapper
return new ATable<TEntity>(refer, cloneFrom);
}
/*
/// <summary>
/// The log.
/// </summary>
/// <param name="format">
/// The format.
/// </param>
/// <param name="args">
/// The args.
/// </param>
public static void Log(string format, params object[] args)
{
if (!Verbose)
{
return;
}
Console.Write("*** ");
if ((args == null) || (args.Length == 0))
{
Console.WriteLine(format);
}
else
{
Console.WriteLine(format, args);
}
}*/
#endregion
#region Methods
/// <summary>
/// Clone an attribute
/// </summary>
/// <param name="attr">
/// </param>
/// <returns>
/// </returns>
private static CustomAttributeBuilder CloneColumn(object attr)
{
Type source = attr.GetType();
Type target = typeof(ColumnAttribute);
var props = new List<PropertyInfo>();
var values = new List<object>();
// Extract properties and their values
foreach (PropertyInfo prop in source.GetProperties())
{
if (!prop.CanRead || !prop.CanWrite)
{
continue;
}
props.Add(target.GetProperty(prop.Name));
values.Add(prop.GetValue(attr, null));
}
// Create a new attribute using the properties and values
return new CustomAttributeBuilder(
target.GetConstructor(Type.EmptyTypes), new object[0], props.ToArray(), values.ToArray());
}
/// <summary>
/// Make a delegate that copy content from "source" to "dest"
/// </summary>
/// <param name="source">
/// Source Type
/// </param>
/// <param name="dest">
/// Destination Type
/// </param>
/// <returns>
/// Executable delegate
/// </returns>
private static Delegate CompileCloning(Type source, Type dest)
{
// Input parameter
ParameterExpression input = Expression.Parameter(source);
// For every property, create a member binding
List<MemberBinding> binds =
source.GetProperties().Select(
prop =>
Expression.Bind(
dest.GetProperty(
prop.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly),
Expression.MakeMemberAccess(input, prop))).Cast<MemberBinding>().ToList();
// Expression of creating the new object
MemberInitExpression body = Expression.MemberInit(
Expression.New(dest.GetConstructor(Type.EmptyTypes)), binds);
// The final lambda
LambdaExpression lambda = Expression.Lambda(body, input);
// MJE
//Log("{0}", lambda.ToString());
// Return the executable delegate
return lambda.Compile();
}
/// <summary>
/// Create a class based on the template interface
/// </summary>
/// <param name="template">
/// </param>
/// <param name="name">
/// </param>
/// <returns>
/// </returns>
private static Type DefineEntityType(Type template, string name)
{
// Prepare the builders if not done
if (_assemblyBuilder == null)
{
_assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
_moduleBuilder = _assemblyBuilder.DefineDynamicModule("Types");
}
// Check if there is already a type created for that table
if (NamedTypes.ContainsKey(name))
{
return NamedTypes[name];
}
// Create the new type
TypeBuilder tbuilder = null;
if (template.IsInterface)
{
tbuilder = DefineInterfaceChild(name, template);
}
else
{
tbuilder = DefineOverriddenChild(name, template);
}
Type final = tbuilder.CreateType();
NamedTypes[name] = final;
return final;
}
/// <summary>
/// The define interface child.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="template">
/// The template.
/// </param>
/// <returns>
/// </returns>
private static TypeBuilder DefineInterfaceChild(string name, Type template)
{
TypeBuilder tbuilder = _moduleBuilder.DefineType(
name, TypeAttributes.Public, typeof(Object), new[] { template });
// Default constructor
tbuilder.DefineDefaultConstructor(MethodAttributes.Public);
// Attach Table attribute
var abuilder = new CustomAttributeBuilder(
typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
new object[0],
new[] { typeof(TableAttribute).GetProperty("Name") },
new object[] { name });
tbuilder.SetCustomAttribute(abuilder);
List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting
// Implement all properties));
foreach (PropertyInfo prop in properties)
{
// Define backing field
FieldBuilder fbuilder = tbuilder.DefineField(
"_" + prop.Name, prop.PropertyType, FieldAttributes.Private);
// Define get method
MethodBuilder pgbuilder = tbuilder.DefineMethod(
"get_" + prop.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.Virtual | MethodAttributes.Final,
prop.PropertyType,
Type.EmptyTypes);
// Define get method body { return _field; }
ILGenerator ilg = pgbuilder.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld, fbuilder);
ilg.Emit(OpCodes.Ret);
// Define set method
MethodBuilder psbuilder = tbuilder.DefineMethod(
"set_" + prop.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.Virtual | MethodAttributes.Final,
null,
new[] { prop.PropertyType });
// Define set method body { _field = value; }
ILGenerator ils = psbuilder.GetILGenerator();
ils.Emit(OpCodes.Ldarg_0);
ils.Emit(OpCodes.Ldarg_1);
ils.Emit(OpCodes.Stfld, fbuilder);
ils.Emit(OpCodes.Ret);
// Define the property
PropertyBuilder pbuilder = tbuilder.DefineProperty(
prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);
// Set get/set method
pbuilder.SetGetMethod(pgbuilder);
pbuilder.SetSetMethod(psbuilder);
// Attach Column attribute
foreach (object attr in prop.GetCustomAttributes(false))
{
if (attr is ColumnAttribute || attr is AlterColumnAttribute)
{
// MJE
//Log("Create column attribute for {0}", prop.Name);
pbuilder.SetCustomAttribute(CloneColumn(attr));
break;
}
}
}
return tbuilder;
}
/// <summary>
/// The define overridden child.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="template">
/// The template.
/// </param>
/// <returns>
/// </returns>
private static TypeBuilder DefineOverriddenChild(string name, Type template)
{
TypeBuilder tbuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, template);
// Default constructor
tbuilder.DefineDefaultConstructor(MethodAttributes.Public);
// Attach Table attribute
var abuilder = new CustomAttributeBuilder(
typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
new object[0],
new[] { typeof(TableAttribute).GetProperty("Name") },
new object[] { name });
tbuilder.SetCustomAttribute(abuilder);
List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting
// Implement all properties));
foreach (PropertyInfo prop in properties)
{
// Define get method
MethodBuilder pgbuilder = tbuilder.DefineMethod(
"get_" + prop.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.Virtual | MethodAttributes.Final,
prop.PropertyType,
Type.EmptyTypes);
// Define get method body { return _field; }
ILGenerator ilg = pgbuilder.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Call, template.GetMethod("get_" + prop.Name));
ilg.Emit(OpCodes.Ret);
// Define set method
MethodBuilder psbuilder = tbuilder.DefineMethod(
"set_" + prop.Name,
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.Virtual | MethodAttributes.Final,
null,
new[] { prop.PropertyType });
// Define set method body { _field = value; }
ILGenerator ils = psbuilder.GetILGenerator();
ils.Emit(OpCodes.Ldarg_0);
ils.Emit(OpCodes.Ldarg_1);
ils.Emit(OpCodes.Call, template.GetMethod("set_" + prop.Name));
ils.Emit(OpCodes.Ret);
// Define the property
PropertyBuilder pbuilder = tbuilder.DefineProperty(
prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);
// Set get/set method
pbuilder.SetGetMethod(pgbuilder);
pbuilder.SetSetMethod(psbuilder);
// Attach Column attribute
foreach (object attr in prop.GetCustomAttributes(false))
{
if (attr is ColumnAttribute || attr is AlterColumnAttribute)
{
// MJE
//Log("Create column attribute for {0}", prop.Name);
pbuilder.SetCustomAttribute(CloneColumn(attr));
break;
}
}
}
return tbuilder;
}
#endregion
/// <summary>
/// A table wrapper implements ITable<TEntity> backed by other ITable object
/// </summary>
/// <typeparam name="TEntity">
/// </typeparam>
public class ATable<TEntity> : ITable<TEntity>
where TEntity : class
{
#region Constants and Fields
/// <summary>
/// Cloning method
/// </summary>
private readonly Delegate _clone;
/// <summary>
/// Backing table
/// </summary>
private readonly ITable _internal;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ATable{TEntity}"/> class.
/// Construct from backing table
/// </summary>
/// <param name="inter">
/// </param>
/// <param name="from">
/// </param>
public ATable(ITable inter, Delegate from)
{
this._internal = inter;
this._clone = from;
}
#endregion
#region Properties
/// <summary>
/// Gets ElementType.
/// </summary>
public Type ElementType
{
get
{
// Use the backing table element
return this._internal.ElementType;
}
}
/// <summary>
/// Gets Expression.
/// </summary>
public Expression Expression
{
get
{
// Use the backing table expression
return this._internal.Expression;
}
}
/// <summary>
/// Gets Provider.
/// </summary>
public IQueryProvider Provider
{
get
{
// Use the backing table provider
return this._internal.Provider;
}
}
#endregion
#region Implemented Interfaces
#region IEnumerable
/// <summary>
/// The get enumerator.
/// </summary>
/// <returns>
/// </returns>
/// <exception cref="NotImplementedException">
/// </exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<TEntity>
/// <summary>
/// The get enumerator.
/// </summary>
/// <returns>
/// </returns>
/// <exception cref="NotImplementedException">
/// </exception>
public IEnumerator<TEntity> GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region ITable<TEntity>
/// <summary>
/// The attach.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
/// <exception cref="NotImplementedException">
/// </exception>
public void Attach(TEntity entity)
{
throw new NotImplementedException();
}
/// <summary>
/// The delete on submit.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
public void DeleteOnSubmit(TEntity entity)
{
// Directly invoke the backing table
this._internal.DeleteOnSubmit(entity);
}
/// <summary>
/// The insert on submit.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
public void InsertOnSubmit(TEntity entity)
{
// Input entity must be changed to backing type
object v = this._clone.DynamicInvoke(entity);
// Invoke the backing table
this._internal.InsertOnSubmit(v);
}
#endregion
#endregion
}
/// <summary>
/// The alter column attribute.
/// </summary>
public class AlterColumnAttribute : Attribute
{
#region Constants and Fields
/// <summary>
/// The _can be null.
/// </summary>
private bool _canBeNull = true;
/// <summary>
/// The _update check.
/// </summary>
private UpdateCheck _updateCheck = UpdateCheck.Always;
#endregion
#region Properties
/// <summary>
/// Gets or sets AutoSync.
/// </summary>
public AutoSync AutoSync { get; set; }
/// <summary>
/// Gets or sets a value indicating whether CanBeNull.
/// </summary>
public bool CanBeNull
{
get
{
return this._canBeNull;
}
set
{
this._canBeNull = value;
}
}
/// <summary>
/// Gets or sets DbType.
/// </summary>
public string DbType { get; set; }
/// <summary>
/// Gets or sets Expression.
/// </summary>
public string Expression { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IsDbGenerated.
/// </summary>
public bool IsDbGenerated { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IsDiscriminator.
/// </summary>
public bool IsDiscriminator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IsPrimaryKey.
/// </summary>
public bool IsPrimaryKey { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IsVersion.
/// </summary>
public bool IsVersion { get; set; }
/// <summary>
/// Gets or sets UpdateCheck.
/// </summary>
public UpdateCheck UpdateCheck
{
get
{
return this._updateCheck;
}
set
{
this._updateCheck = value;
}
}
#endregion
}
}
}
A: Linq-to-Sql cannot materialize interfaces. It needs a class specification to know what instances it should create from a query. The exception message is elusive, to say the least. I don't know why it isn't more to the point.
Note that the class you want to materialize must have been mapped, or: it must be in the dbml. I say this because your ITIPO class is not partial, which makes me wonder how you can make it implement an interface (well, maybe you just slimmed down the code).
Side note: don't use all capitals for class names, and prefix an interface specification with "I", not a class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13911036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android kotlin shared preferences unresolved reference getSharedPreferences error I am learning Kotlin by trying to build a small app that find and and remember last connected BLE device. To recognize the last connected device I decide to save its MAC address using shared preferences (is that the best way to do that is also a question). I use a tutorial online and it worked well (I didn't remember the page) but today when I open the project to continue the job it gives me error - unresolved reference getSharedPreferences. My question is what is the problem - I get lost :) Here is the class where I have the error row 23.
import android.content.Context
import android.content.SharedPreferences
interface PreferencesFunctions {
fun setDeviceMAC(deviceMAC: String)
fun getDeviceMAC(): String
fun setLastConnectionTime(lastConnectionTime: String)
fun getLastConnectionTime(): String
fun clearPrefs()
}
class PreferenceManager(context: ScanResultAdapter.ViewHolder) : PreferencesFunctions{
private val PREFS_NAME = "SharedPreferences"
private var preferences: SharedPreferences
init {
preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
}
override fun setDeviceMAC(deviceMAC: String) {
preferences[DEVICE_MAC] = deviceMAC
}
override fun getDeviceMAC(): String {
return preferences[DEVICE_MAC] ?: ""
}
override fun setLastConnectionTime(lastConnectionTime: String) {
preferences[LAST_CONNECTION_TIME] = lastConnectionTime
}
override fun getLastConnectionTime(): String {
return preferences[LAST_CONNECTION_TIME] ?: ""
}
override fun clearPrefs() {
preferences.edit().clear().apply()
}
companion object{
const val DEVICE_MAC = "yyyyyyy"
const val LAST_CONNECTION_TIME = "zzzzzzz"
}
}
A: Your arguement context is not a acitivity or fragment, and you need those two to call getSharedPreferences method.
class PreferenceManager(context: Context) : PreferencesFunctions{
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66820897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MvvmCross throwing InvalidStackFrameException I am using MvvmCross to develop an ios app. Everything worked fine until suddenly I got the following exception:
Mono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.
at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301
at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448
at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225
at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122
at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68
at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138
at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106 Mono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.
at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301
at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448
at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225
at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122
at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68
at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138
at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106
It is important to say that this only happens on the device, everything works perfectly on the simulator...
I have fiddled with the code to come to a conclusion once I removed the following code everything worked:
var source = new MvxSimpleTableViewSource (MainTable, RecomendationTemplate.Key, RecomendationTemplate.Key);
MainTable.Source = source;
var set = this.CreateBindingSet<MainPage, MainPageViewModel> ();
set.Bind (source).To (vm => vm.Recomendations);
set.Apply ();
After that I have tried to use a difference cell template. I started with an empty one and it worked. but once I added the DelayBind mehtod I kept on getting the following exception... I have no idea how to move forward from here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21215725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sql Server Stored Procedure not executing from MVC I am trying to execute a stored procedure in my Sql Server Database from an Asp.Net MVC project. I have set it up in a way that I can use it for testing purposes, which is why the variable "procedureTest" is a constant value (I know that "2044" is an existing record in my database). I will change this once I accomplish a successful run. Also, I know that my stored procedure works because I have executed it in Sql Server Management Studio successfully. The procedure has the task of adding ID from one table to another, but I have yet to see it appear in this table. I am not receiving an error in my catch block so I am kind of lost at the moment. I could definitely use your help.
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
int procedureTest = 2044;
var command = new SqlCommand("SELECT ID FROM Images WHERE ID = @id", connection);
var paramDate = new SqlParameter("@id", procedureTest);
command.Parameters.Add(paramDate);
var reader = command.ExecuteReader();
while (reader.Read())
{
var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
var paramId = new SqlParameter("@ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
string exceptionCause = String.Format("An error occurred: '{0}'", e);
System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
}
Stored Procedure:
CREATE PROCEDURE addToNotificationTable @ID int
AS
Insert NotificationTable (ID)
SELECT ID
FROM Images
Where ID = @ID
A: Change you code like this
while (reader.Read())
{
var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
var paramId = new SqlParameter("@ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
storedProcCommand.ExecuteNonQuery();
}
A: First of all, you missed to specify the command type. Also using EXEC in SqlCommand is not a proper way.
Please try with the below code
while (reader.Read())
{
using(SqlCommand storedProcCommand = new SqlCommand("addToNotificationTable", connection)) //Specify only the SP name
{
storedProcCommand.CommandType = CommandType.StoredProcedure; //Indicates that Command to be executed is a stored procedure no a query
var paramId = new SqlParameter("@ID", reader.GetInt32(0));
storedProcCommand.Parameters.Add(paramId);
storedProcCommand.ExecuteNonQuery()
}
}
Since you are calling the sp inside a while loop, wrap the code in using() { } to automatically dispose the command object after each iteration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31530797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to insert special HTML-symbols with HAML When I'm saying:
%p= item.price + " dollars"
I'm getting
50  ;dollars
instead of having non-breakable space symbol.
How to insert this and another special symbols using HAML ?
A: How about
%p= item.price + " dollars".html_safe
A: This answer is for a slightly different question but I found this question searching for it...
If you have a submit tag %input{ :type => "submit", :value => " dollars", :name => "very_contrived" } even if you throw an html_safe on the :value it will not evaluate the html.
The solution is to use the rails helper... duh
= submit_tag " dollars".html_safe
this is pretty obvious but it tripped me up. Legacy code + rails upgrade = this kind of stuff :P
A: Use != instead of =
See "Unescaping HTML" in the haml reference: http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html
A: The interpolation option:
%p= "#{item.price} dollars".html_safe
A: I tried using html_safe in different ways, but none worked. Using \xa0 as suggested by ngn didn't work, either, but it got me to try the Unicode escape of the non-breaking space, which did work:
"FOO\u00a0BAR"
and .html_safe isn't even needed (unless something else in the string needs that, of course).
The Ruby Programming Language, first edition, says: "In Ruby 1.9, double-quoted strings can include arbitrary Unicode escape characters with \u escapes. In its simplest form, \u is followed by exactly four hexadecimal digits ..."
A: You could use \xa0 in the string instead of . 0xa0 is the ASCII code of the non-breaking space.
A: I prefer using the character itself with the escaped HTML method with most symbols other than the whitespace characters. That way i don't have to remember all the html codes. As for the whitespace characters i prefer to use CSS, this is a much cleaner way.
%p&= "#{item.price} $%&#*@"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6305414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Trying to replace values in a data frame with other values I have a list of vectors, L1, and a data frame, df2. I want to take values from df2 and replace the values of L1 with these. For example, when ABCC10 of L1 says "TCGA_DD_A1EG", I want to replace this with the value, 2.193205, from row 1 (ABCC10), column 3 (TCGA.DD.A1EG). I want to do this with every value.
L1 looks like this:
$ABCC10
[1] "TCGA_DD_A1EG" "TCGA_FV_A3R2" "TCGA_FV_A3I0" "TCGA_DD_A1EH" "TCGA_FV_A23B"
$ACBD6
[1] "TCGA_DD_A1EH" "TCGA_DD_A3A8" "TCGA_ES_A2HT" "TCGA_DD_A1EG" "TCGA_DD_A1EB"
df2 looks like this:
TCGA.BC.A10Q TCGA.DD.A1EB TCGA.DD.A1EG TCGA.DD.A1EH TCGA.DD.A1EI TCGA.DD.A3A6 TCGA.DD.A3A8
ABCC10 2.540764 0.4372165 2.193205 3.265756 0.6060301 2.927072 0.6799514
ACBD6 1.112432 0.4611697 1.274129 1.802985 -0.0475743 1.071064 0.4336301
TCGA.ES.A2HT TCGA.FV.A23B TCGA.FV.A3I0 TCGA.FV.A3R2
ABCC10 -0.08129554 2.2963764 3.196518 0.8595943
ACBD6 1.76935812 0.3644397 1.392206 1.0282030
A: One approach could be like
df1 = list(ABCC10 = c("TCGA_DD_A1EG", "TCGA_FV_A3R2", "TCGA_FV_A3I0", "TCGA_DD_A1EH", "TCGA_FV_A23B"),
ACBD6 = c("TCGA_DD_A1EH", "TCGA_DD_A3A8", "TCGA_ES_A2HT", "TCGA_DD_A1EG", "TCGA_DD_A1EB"))
df2 = data.frame(TCGA.BC.A10Q = c(2.540764, 1.112432),
TCGA.DD.A1EB = c(0.4372165, 0.4611697),
TCGA.DD.A1EG = c(2.193205, 1.274129),
TCGA.DD.A1EH = c(3.265756, 1.802985),
TCGA.DD.A1EI = c(0.6060301, -0.0475743),
TCGA.DD.A3A6 = c(2.927072, 1.071064),
TCGA.DD.A3A8 = c(0.6799514, 0.4336301),
TCGA.ES.A2HT = c(-0.08129554, 1.76935812),
TCGA.FV.A23B = c(2.2963764, 0.3644397),
TCGA.FV.A3I0 = c(3.196518, 1.392206),
TCGA.FV.A3R2 = c(0.8595943, 1.0282030),
row.names = c('ABCC10', 'ACBD6'))
for(i in 1:length(df1)){
for(j in 1:length(df1[[1]])){
df1[names(df1)[i]][[1]][j] = df2[names(df1)[i],gsub("_",".",df1[names(df1)[i]][[1]][j])]
}
}
Output is:
$ABCC10
[1] "2.193205" "0.8595943" "3.196518" "3.265756" "2.2963764"
$ACBD6
[1] "1.802985" "0.4336301" "1.76935812" "1.274129" "0.4611697"
Hope this helps!
A: Maybe the following will do it.
First, make up some data, a list and a data.frame.
df1 <- list(A = letters[1:3], B = letters[5:7])
df2 <- data.frame(a = rnorm(2), b = rnorm(2), c = rnorm(2),
e = rnorm(2), f = rnorm(2), g = rnorm(2))
row.names(df2) <- c('A', 'B')
Now the code.
for(i in seq_along(df1)){
x <- gsub("_", ".", df1[[i]])
inx <- match(x, names(df2))
df1[[i]] <- df2[i, inx]
}
df1
In my tests it did what you want. If it doesn't fit your real problem, just say so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45947581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Binding value in JSP page I have a XML value in controller and i'm passing that value to jsp page and binding as shown in the below code.
<input type="hidden" id="thisField" name="inputName" value='${xml}'/>
It is binding the value as shown in the below.
<input type="hidden" id="thisField" name="inputName" value='
<?xml version="1.0" encoding="UTF-8"?>
<Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0">
<Docs>
<InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>
</Docs>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>
<KeyInfo>
<X509Data>
<X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>
<X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</Esign>'/>
But i want to bind like below without spaces.
<input type="hidden" id="thisField" name="inputName" value='<?xml version="1.0" encoding="UTF-8"?><Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0"><Docs><InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash></Docs><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue></Reference></SignedInfo><SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=Rbl Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName><X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate></X509Data></KeyInfo></Signature></Esign>'/>
Is there any way to bind like as shown in the above?
A: You can perform a manipulation of the xml string in your controller with a little regex to eliminate the newlines and whitespace.
Here is a little java app to show the regex in work against your xml string.
public class StripXmlWhitespace {
public static void main (String [] args) {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
" <Esign AuthMode=\"1\" aspId=\"ASPRBLBMUMTEST043\" ekycId=\"448988431774\" ekycIdType=\"A\" ekycMode=\"U\" organizationFlag=\"N\" preVerified=\"n\" responseSigType=\"pkcs7\" responseUrl=\"http://10.80.49.41\" sc=\"Y\" ts=\"2018-01-19T11:42:55\" txn=\"UKC:eSign:6539:20180119114250963\" ver=\"2.0\">\n" +
" <Docs>\n" +
" <InputHash docInfo=\"Signing pdf\" hashAlgorithm=\"SHA256\" id=\"1\">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>\n" +
" </Docs>\n" +
" <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
" <SignedInfo>\n" +
" <CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n" +
" <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n" +
" <Reference URI=\"\">\n" +
" <Transforms>\n" +
" <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n" +
" </Transforms>\n" +
" <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n" +
" <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>\n" +
" </Reference>\n" +
" </SignedInfo>\n" +
" <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>\n" +
" <KeyInfo>\n" +
" <X509Data>\n" +
" <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>\n" +
" <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>\n" +
" </X509Data>\n" +
" </KeyInfo>\n" +
" </Signature>\n" +
" </Esign>";
String output = xmlString.replaceAll(">\\s+<", "><");
System.out.println(xmlString);
System.out.println(output);
}
}
All you need in your controller is the regex.
xml = xmlString.replaceAll(">\\s+<", "><");
Essentially unformat the xml before you send it bind it to the view. I hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48564808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: REGEX to extract multiple name/value tokens (vbscript) Given a template that looks like this:
<td class="creditapp heading">{*}Street Address:</td>
<td colspan=2 class="tdaddressblock">
<!-- @template="addressBlock" for="buyer" prev="" @-->
^^ might be a space here, might not ^^ always a space here
</td>
I need to read the name=value pairs out of the comment, plus the whole string so it can be replaced. Names could be any alpha-numeric with no spaces, values could contain anything except double quotes, will be short as possible, and will always be surrounded by double-quotes.
So, possible formats:
<!-- @pizza="yes" @-->
<!-- @ingredients="cheese sauce meat" @-->
<!-- @ drinks="yes, please" breadsticks="garlic, butter (lots); cheese" @-->
I've tried a dozen different variations, but the most successful I've been so far is to get the first name="value" pair and nothing else, or I get the whole page worth of stuff. So the desired matches are
[1] <!-- @ drinks="yes, please" breadsticks="garlic, butter (lots); cheese" @-->
[2] drinks
[3] yes, please
[4] breadsticks
[5] garlic, butter (lots); cheese
The closest I've come so far is
<!-- @(( |)([\w]+)="(.*?)")+ @-->
but it only returns the last pair, not all of them.
A: Implementation of the 2 step processes @sln mentioned in VBScript:
Option Explicit
Dim rCmt : Set rCmt = New RegExp
rCmt.Global = True
rCmt.Pattern = "<!-- @[\s\S]+?@-->"
Dim rKVP : Set rKVP = New RegExp
rKVP.Global = True
rKVP.Pattern = "(\w+)=""([^""]*)"""
Dim sInp : sInp = Join(Array( _
"<td class=""creditapp heading"">{*}Street Address:</td>" _
, "<td colspan=2 class=""tdaddressblock"">" _
, "<!-- @template=""addressBlock"" for=""buyer"" prev="""" @-->" _
, "</td>" _
, "<!-- @ pipapo=""i dont care""" _
, "rof=""abracadabra"" prev="""" @-->" _
), vbCrLf)
WScript.Echo sInp
WScript.Echo "-----------------"
WScript.Echo rCmt.Replace(sInp, GetRef("fnRepl"))
WScript.Quit 0
Function fnRepl(sMatch, nPos, sSrc)
Dim d : Set d = CreateObject("Scripting.Dictionary")
Dim ms : Set ms = rKVP.Execute(sMatch)
Dim m
For Each m In ms
d(m.SubMatches(0)) = m.SubMatches(1)
Next
fnRepl = "a comment containing " & Join(d.Keys)
End Function
output:
cscript 45200777-2.vbs
<td class="creditapp heading">{*}Street Address:</td>
<td colspan=2 class="tdaddressblock">
<!-- @template="addressBlock" for="buyer" prev="" @-->
</td>
<!-- @ pipapo="i dont care"
rof="abracadabra" prev="" @-->
-----------------
<td class="creditapp heading">{*}Street Address:</td>
<td colspan=2 class="tdaddressblock">
a comment containing template for prev
</td>
a comment containing pipapo rof prev
As Mr. Gates Doc for the .Replace method sucks, see 1, 2, 3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45200777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: find out what instructions write to this memory address olly dbg cheat engine Is there an option in ollydbg to find out what pieces of code write to a memory address ? Just like Cheat Engine shows all the assembly instructions that write to a specific address.
"breakpoint --> memory" does not work.
A: Yes,
With olly open and debugging a certain program, go to View tab>Memory or Alt+M
then, find the memory address (first you have to choose the memory part of the program like .data or .bss) and then click on the address (or addresses selecting multiple with Shift) with the right mouse button and hover to Breakpoint then you'll be able to choose the to break the program when it writes or reads the address
A good thing to do is first find the address on cheatEngine then use the breakpoint on ollydbg.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27363155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: setNeedsDisplay not resulting in dirtyRect filling entire view I am having a confusing issue. I try to draw a graph, and call setNeedsDisplay each time new data is added to the graph.
The graph receives new data via addData:(NSNotification*)theNote, which then tries several ways to call setNeedsDisplay to redraw the view. The data does not get redrawn properly, however, at this time. If I drag the window to another screen, or if I click on the graph and call setNeedsDisplay from mouseDown then the view is redrawn correctly. By monitoring the size of dirtyRect using NSLog, I have tracked the problem to a too small dirtyRect. But I cannot even guess how to correct this. Any ideas out there?
//
// graphView.m
// miniMRTOF
//
// Created by γ·γ₯γΌγͺ γγΌγΏγΌ on 8/1/16.
// Copyright Β© 2016 γ·γ₯γΌγͺ γγΌγΏγΌ. All rights reserved.
//
#import "graphView.h"
@implementation graphView
- (id)initWithFrame:(NSRect)frame{
self = [super initWithFrame:frame];
if (self) {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(addData:) name:AddDataNotification object:nil];
theData = [[NSMutableArray alloc] init];
NSLog(@"graphView initialized");
}
return self;
}
-(void)addData:(NSNotification*)theNote{
NSLog(@"graphView has gotten the note");
NSMutableArray *theThermalArray = [[NSMutableArray alloc] init];
theThermalArray = [[theNote userInfo] objectForKey:@"theThermals"];
float ave = 0;
int n = 0;
for (int i=0; i<16; i++){
float f_i = [[theThermalArray objectAtIndex:i] floatValue];
ave += f_i;
if(f_i != 0) n++;
}
ave /= n;
[theData addObject:[NSNumber numberWithFloat:ave]];
NSLog(@"graphView has added %0.3f and now has %lu components", ave, (unsigned long)[theData count]);
[self setNeedsDisplay:YES];
[[self.window contentView] setNeedsDisplay:YES];
[self performSelectorOnMainThread:@selector(redraw) withObject:nil waitUntilDone:YES];
}
-(void)redraw{
[self setNeedsDisplay:YES];
[[self.window contentView] setNeedsDisplay:YES];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
NSLog(@"dirtyRect: x:%0.2f, y:%0.2f, w:%0.2f, h:%0.2f", dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);
float xScale = ([self bounds].size.width)/((float)[theData count]+1e-3);//(maxX - minX);
float yScale = [self bounds].size.height/(maxT - minT);
[[NSColor whiteColor] set];
NSRect fillArea = [self bounds];
[NSBezierPath fillRect:fillArea];
if(dirtyRect.size.height < 100){
NSLog(@"small dirtyRect");
[[NSColor grayColor] set];
[NSBezierPath fillRect:dirtyRect];
}
dirtyRect = [self bounds];
int dataCount = (int)[theData count];
NSBezierPath *pathForFrame = [[NSBezierPath alloc] init];
NSPoint P0 = {1,1};
NSPoint P1 = {1, [self bounds].size.height};
NSPoint P2 = {[self bounds].size.width, 1};
[pathForFrame moveToPoint:P0];
[pathForFrame lineToPoint:P1];
[pathForFrame moveToPoint:P0];
[pathForFrame lineToPoint:P2];
[[NSColor redColor] set];
[pathForFrame stroke];
NSLog(@"drawing %i points", dataCount);
NSBezierPath *pathForPlot = [[NSBezierPath alloc] init];
if(dataCount<maxRawPlotData){
if(dataCount>1){
NSPoint p1;
p1.y = [[theData objectAtIndex:0] floatValue];
p1.x = (0-minX)*xScale;
p1.y = (p1.y-minT)*yScale;
[pathForPlot moveToPoint:p1];
NSLog(@"point: %0.1f, %0.1f", p1.x, p1.y);
}
for(int i=1; i<dataCount; i++){
NSPoint p;
p.y = [[theData objectAtIndex:i] floatValue];
p.x = (i-minX)*xScale;
p.y = (p.y-minT)*yScale;
[pathForPlot lineToPoint:p];
NSLog(@"point: %0.1f, %0.1f", p.x, p.y);
}
}
[[NSColor blackColor] set];
[pathForPlot stroke];
[txtMaxX setStringValue:[NSString stringWithFormat:@"%0.0f",maxX]];
}
-(void)controlTextDidEndEditing:(NSNotification *)obj{
NSLog(@"controlTextDidEndEditing");
if([[obj object] isEqualTo:txtMaxT]){
maxT = [txtMaxT floatValue];
[txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
}
else if([[obj object] isEqualTo:txtMinT]){
minT = [txtMinT floatValue];
[txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
}
else if([[obj object] isEqualTo:txtMaxX]){
maxX = [txtMaxX floatValue];
}
else if([[obj object] isEqualTo:txtMinX]){
minX = [txtMinX floatValue];
}
else NSLog(@"How'd we get here?");
[[[obj object] window] makeFirstResponder:[[obj object] window].contentView];
[self setNeedsDisplay:YES];
[self display];
}
-(void)mouseDown:(NSEvent *)theEvent{
NSLog(@"mousedown");
[self setNeedsDisplay:YES];
}
@end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38696797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JIRA Xray Cloud - Import Execution Results using REST API Hi I am using JIRA Cloud and trying to import execution result using REST API.
End Point URL - https://xray.cloud.getxray.app/api/v1/import/execution
Request Type - POST
Content-Type - application/json
Authorization: Bearer ""
Body -
{
"info" : {
"project": "QAUT",
"summary" : "Execution of automated tests using UFT",
"description" : "This execution is automatically created when importing execution results from UFT",
"startDate" : "2022-09-19T11:47:35+01:00",
"finishDate" : "2022-09-19T11:53:00+01:00",
"testPlanKey" : "QAUT-1"
},
"tests" : [
{
"testKey" : "QAUT-3",
"start" : "2022-09-19T11:47:35+01:00",
"finish" : "2022-09-19T11:50:56+01:00",
"actualResult" : "Successful execution",
"status" : "PASSED"
}
]
}
I am getting below errors:
Response code - 400
Response Body -
{
"error": "Result is not valid Xray Format"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73788673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unexpected behavior Using React useState, Very strange output I am a newbie in React. I was experimenting around to see how things work,
and I found a very strange Behavior of React or useState whatever you want to call it.
Please, Someone, explain, what is going on and how this piece of coding is working.
const {useState} = React;
let referceGiver = 0;
function giveNewRef() {
let a = referceGiver;
console.log("Making New Reference | Ref = ", a);
referceGiver++;
return a;
}
function App() {
let v = "10";
console.log("%cIniside Function", "background-color:red", `| v = ${v}`);
let [val, setVal] = useState('30');
const currentReference = giveNewRef();
console.log("Outer Function Reference = ", currentReference)
console.log("Value of UseState Val = ", val);
function clicked() {
v += ' 20';
console.log("Inner Function Reference = ", currentReference);
console.log("Value of V = ", v);
setVal(v);
}
console.log("%cGoing To Return", "background-color:green");
console.log('-----------------------------')
return (
<div>
<h1>{val + " " + Math.random()}</h1>
<button onClick={clicked} > Click </button>
</div>
);
}
ReactDOM.render(<App/>, document.querySelector('#mount'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="mount"/>
Output of the above code
Tell me why:
*
*inner and outer reference is different
*useState does not change 2 times but changes a third time
*giveNewRef() increasing value by 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68496796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing the shape of a new assigned variable in Tensorflow if you change a tf.Variable using tf.assign with validate_shape=False the shape is not updated.
But if I use set_shape to set the new (correct) shape I get a ValueError.
Here a quick example:
import tensorflow as tf
a = tf.Variable([3,3,3])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# [3 3 3]
print(sess.run(a))
sess.run(tf.assign(a, [4,4,4,4], validate_shape=False))
# [4 4 4 4]
print(sess.run(a))
# (3,)
print(a.get_shape())
# ValueError: Dimension 0 in both shapes must be equal, but are 3 and 4. Shapes are [3] and [4].
a.set_shape([4])
How do I change the shape of the Variable?
Note: I am aware that the code works if I use a = tf.Variable([3,3,3], validate_shape=False) but in my context I will not be able to initialize the variable myself.
A: Tell the static part of the graph that the shape is unknown from the start as well.
a = tf.Variable([3,3,3], validate_shape=False)
Now, to get the shape, you cannot know statically, so you have to ask the session, which makes perfect sense:
print(sess.run(tf.shape(a)))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53611227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to remove backup logs on application startup I have a RotatingFileHandler with mode=w, maxBytes=20000000 and backupCount=10 as shown below:
[loggers]
keys=root
[logger_root]
level=INFO
handlers=file
[formatters]
keys=simple
[formatter_simple]
format=[%(levelname)s] %(asctime)s : %(name)s - %(message)s
datefmt=%H:%M:%s
[handlers]
keys=file
[handler_file]
class=handlers.RotatingFileHandler
formatter=simple
level=INFO
args=(log_directory,'w', 20000000, 10)
This means that after a period of time, 11 distinct log files will be present ( test.log, test.log.1, ..., test.log.10 ). My requirement is when the application is started, I want to delete all of the backup log files (test.log.1, ..., test.log.10). The content of test.log (current) log file will be removed anyway because mode is set to w.
A: That task is not under logging scope, you should "manually" delete them upon application start. Use os or shutil.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56890049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to debug Spring Cloud Kubernetes Configuration Watcher when it is not working as expectted There are two components in my k8s namespace.
*
*The first component is a simple Spring Boot Web Service with actuator/refresh endpoint exposed. I have mannualy make post request to the endpoint and it will trigger a configuration context refresh succesfully.
*The second component is Spring Cloud Kubernetes Configuration Watcher which I pull the image per official document guidance and make it run in my k8s env. Per official spring document, it should detect the changes on configmap with label spring.cloud.kubernetes.config="true" and make post request to the actuator/refresh endpoint of the application whose spring.application.name is equal to the configmap name.
The second component is not working as expectted, and I don't know how to trouble shoot the root cause.
My Springboot application is called spring-boot-demo, the configmap is also named as spring-boot-demo. But I never find any mentions of "spring-boot-demo" in Spring Cloud Kubernetes Configuration Watcher's log and nor can I assure if it has sent post request to related endpoint.
I can only see the logs showed up repeatedly below:
2021-11-22 02:58:53.332 INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 02:58:53.332 INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.555 WARN 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : ConfigMaps watch closed
io.fabric8.kubernetes.client.WatcherException: too old resource version: 5491278743 (5554041906)
at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onStatus(AbstractWatchManager.java:263) [kubernetes-client-5.5.0.jar:na]
at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onMessage(AbstractWatchManager.java:247) [kubernetes-client-5.5.0.jar:na]
at io.fabric8.kubernetes.client.dsl.internal.WatcherWebSocketListener.onMessage(WatcherWebSocketListener.java:93) [kubernetes-client-5.5.0.jar:na]
at okhttp3.internal.ws.RealWebSocket.onReadMessage(RealWebSocket.java:322) [okhttp-3.14.9.jar:na]
at okhttp3.internal.ws.WebSocketReader.readMessageFrame(WebSocketReader.java:219) [okhttp-3.14.9.jar:na]
at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.java:105) [okhttp-3.14.9.jar:na]
at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.java:273) [okhttp-3.14.9.jar:na]
at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:209) [okhttp-3.14.9.jar:na]
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) [okhttp-3.14.9.jar:na]
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) [okhttp-3.14.9.jar:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_312]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_312]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_312]
Caused by: io.fabric8.kubernetes.client.KubernetesClientException: too old resource version: 5491278743 (5554041906)
... 13 common frames omitted
2021-11-22 03:34:06.605 INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 03:34:06.605 INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.607 INFO 1 --- [192.168.0.1/...] s.c.k.f.c.Fabric8ConfigMapPropertySource : Loading ConfigMap with name 'spring-cloud-kubernetes-configuration-watcher' in namespace 'my-namespace'
2021-11-22 03:34:06.621 WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils : config-map with name : 'spring-cloud-kubernetes-configuration-watcher' not present in namespace : 'my-namespace'
2021-11-22 03:34:06.625 WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils : config-map with name : 'spring-cloud-kubernetes-configuration-watcher-kubernetes' not present in namespace : 'my-namespace'
The docker image I use is springcloud/spring-cloud-kubernetes-configuration-watcher:2.1.0-RC1
Any hint to debug this issue is appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70061702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS mobile devices and hamburger menu I have designed a website that uses a CSS hamburger menu to activate a slidebar with a links to different webpages on the site.
I also have written an iPhone/andriod apps that need to have an hamburger menu that open a slider work that run swift and android code.
I want to add to the iphone/android hamburger slidebar links to the website (which has it own hamburger menu)
How can I test on the website if it a mobile device or a PC, so I can turn off if "Website" hamburger if its a mobile, since I already have and need the hamburger menu on the mobile.
I have php on the website so I can remove the hamburger menu on the website if its a mobile.
This is the main page
<html>
<div class="w3-sidebar w3-bar-block w3-card-2 w3-animate-left" style="display:none" id="mySidebar">
<button class="w3-bar-item w3-button w3-large" onclick="w3_close()">Home</button>
<a href="menu_01_angular.php" class="w3-bar-item w3-button">Link 1</a>
<a href="#" class="w3-bar-item w3-button">Link 2</a>
<a href="#" class="w3-bar-item w3-button">Link 3</a>
</div>
<div zclass="w3-main" id="main">
<div class="w3-teal">
<button class="w3-button w3-teal w3-xlarge" onclick="w3_open()">☰</button>
<div class="w3-container">
<h1>My Page</h1>
</div>
Thanks
A: so there are a few ways of doing this, but a really simple one is something like this:
var width = $(window).width(); //jquery
var width = window.innerWidth; //javascript
if(width > 1000){do large screen width display)
else{handle small screen}
of course 1000 is just an arbitrary number. it gets tricky because when you consider tables, there really are screens of all sizes so its up to you to determine what belongs where
A:
How can I test on the website if it a mobile device or a PC, so I can
turn off if "Website" hamburger if its a mobile,
If I understood you correctly, you could use CSS @media -rules, to setup CSS rules that only apply to smaller devices. Below is a simple code-snippet example of a CSS media-query.
@media (min-width: 700px), handheld
{
.w3-sidebar
{
display: none;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45897302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NativeScript Typescript: JSON Array to Typescript Typed Array I need your help, I'm learning NativeScript, here I read the txt file which has JSON data below output. After I fetch them I want to assign it to Array countries. But no luck :(
public countries: Array
console.log(response)
console.log(JSON.parse(JSON.stringify(response)))
Output:
[
{
"name": "Afghanistan",
"code": "AF"
},
{
"name": "Albania",
"code": "AL"
}
]
Please help.
Regards,
A: This is an Array<any>:
[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]
You need to convert it to a Array<Country>, Example:
result.forEach((e) => { countries.push(new Country(e.name, e.code))
That, or you can change the return of the function that reads the txt to Array<Country>
A: finally got it via below code...
let elements: Array<Country> = JSON.parse(JSON.stringify(response))
.map((item:Country) =>
{
console.log(item.name + ' < - >' + item.code);
})
Thanks All :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43926540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery array confusion I have a web page with a bunch of tables decorated with the datatable jquery plugin. When the page is loaded, they're hidden. Then I have a function that toggles them based on the index:
function expand_job(i) {
$(".dataTables_wrapper")[i].show();
}
But it didn't work. Browser complains that show() is not a function. As a work around, I'm doing something like this:
function expand_job(i) {
$(".dataTables_wrapper").each( function(idx) {
if ( i == idx ) {
$(this).slideToggle(300);
}
});
}
That works fine but it's..... I just can't let this go.
So why did the first piece of code not work? Is it because [i] takes an jquery object into and normal JS object and as a result lost the jquery functionality?
Thanks,
A: Use .eq():
$(".dataTables_wrapper").eq(i).show();
jQuery arrays contain the underlying DOM elements at each index, so when you access them the DOM functions are available but not the jQuery methods.
A: $(".dataTables_wrapper")[i]
returns a std java script object, not a jQuery object so you could:
$($(".dataTables_wrapper")[i]).show()
or use nth child or similar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6787741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: redux differentiation with context api My understanding is that React's Context API was essentially introduced for quick and dirty global state management, particularly before Redux Toolkit was introduced to simplify the overhead of implementing Redux.
My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).
I recently explained that downside to someone and he asked why that wouldn't be the case with Redux. He said Redux uses the Context API under the covers which appears to be the case based on some googling:
https://react-redux.js.org/using-react-redux/accessing-store#:~:text=Internally%2C%20React%20Redux%20uses%20React's,object%20instance%20generated%20by%20React.
A few questions:
1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?
2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?
3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?
4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render? I would assume that there's somevtype of mapping layer but I'd be interested to get some more insight into the specific implementation details
A:
My understanding is that React's Context API was essentially introduced for quick and dirty global state management
That's a common misunderstanding. Context is not a state management system, any more than props is a state management system. Context (like props) is a way to get data from one component to another. The difference is that props always passes the data to direct children, while context makes the data available to whichever random components in a subtree are interested.
My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).
This is true. Similarly, if you change props, the component that receives those props must rerender
1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?
Of the specific components that are listening to that context, yes.
2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?
React-redux does use context, yes. Pure redux and redux toolkit don't, since they're general purpose libraries not directly related to react, but I think you meant react-redux.
That <Provider store={store}> that you must render at the top of a react-redux app is there to provide a context to the components underneath it. Components that call hooks like useSelector or useDispatch then use the context to find the store that they should interact with.
3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?
Context has existed for a long time, but it used to be an unofficial feature. They've also made it easier to use over time.
4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?
The context is only providing a minimal amount of things to the child components, most importantly the store object. The reference to the store object does not typically change, so since the context value does not change, the child components do not need to render. To see exactly what it's providing, see this code: https://github.com/reduxjs/react-redux/blob/master/src/components/Provider.tsx#L33
The contents of the store does change, but that's not what the context is providing. To get the contents of the store, the individual components subscribe to the store, using redux's store.subscribe, plus a special hook called useSyncExternalStore. Basically, redux fires an event when the store's state is updated, and then the individual components set their own local state if it's a change they care about. This local state change is what causes the rerender.
If you're writing code that uses context, you're rarely going to be doing things fancy enough to require useSyncExternalStore or a custom subscription system. So the main things you'll want to keep in mind are:
*
*Keep the context focused on a single task. For example, if you have a theme object to control your app's colors, and also a user object which describes who is currently logged in, put these in different contexts. That way a component that just cares about the theme doesn't need to rerender when the user changes, and vice versa.
*If your context value is an object, memoize it so it's not changing on every render (see this documentation)
A: I'm a Redux maintainer. @NicholasTower gave a great answer, but to give some more details:
Context and Redux are very different tools that solve different problems, with some overlap.
Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components. It's up to you to decide what that value is, and how it's created. Typically, that's done using data from React component state, ie, useState and useReducer. So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.
Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed. It also gives your whole app the ability to access any piece of state in any component.
In addition, there are some distinct differences between how Context and (React-)Redux pass along updates. Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.
Context is a great tool by itself, and I use it frequently in my own apps. But, Context doesn't "replace Redux". Sure, you can use both of them to pass data down, but they're not the same thing. It's like asking "Can I replace a hammer with a screwdriver?". No, they're different tools, and you use them to solve different problems.
Because this is such a common question, I wrote an extensive post detailing the differences:
Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)
To answer your questions specifically:
*
*Yes, updating a Context value forces all components consuming that context to re-render... but there's actually a good chance that they would be re-rendering anyway because React renders recursively by default, and setting state in a parent component causes all components inside of that parent to re-render unless you specifically try to avoid it. See my post A (Mostly) Complete Guide to React Rendering Behavior, which explains how all this works.
*Yes, React-Redux does use Context internally... but only to pass down the Redux store instance, and not the current state value. This leads to very different update characteristics. Redux Toolkit, on the other hand, is just about the Redux logic and not related to any UI framework specifically.
*Context was not introduced to be an alternative to Redux. There was a "legacy Context" API that existed in React well before Redux itself was created, and React-Redux used that up through v5. However, that legacy context API was broken in some key ways. The current React Context API was introduced in React 16.3 to fix the problems in legacy Context, not specifically to replace Redux.
*React-Redux uses store subscriptions and selectors in each component instance, which is a completely different mechanism than how Context operates.
I'd definitely suggest reading the posts I linked above, as well as these other related posts:
*
*Redux - Not Dead Yet!
*When (and when not) to Reach for Redux
*React, Redux, and Context Behavior.
A: Original blog post by Mark Erikson:
I'll just copy paste some info, but here's the original source and I recommend going directly here: https://blog.isquaredsoftware.com/2020/01/blogged-answers-react-redux-and-context-behavior/
More links here:
*
*https://github.com/markerikson/react-redux-links
*https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/
*https://medium.com/async/how-useselector-can-trigger-an-update-only-when-we-want-it-to-a8d92306f559
An explanation of how React Context behaves, and how React-Redux uses Context internally
There's a couple assumptions that I've seen pop up repeatedly:
*
*React-Redux is "just a wrapper around React context"
*You can avoid re-renders caused by React context if you destructure the context value
Both of these assumptions are incorrect, and I want to clarify how they actually work so that you can avoid mis-using them in the future.
For context behavior, say we have this initial setup:
function ProviderComponent() {
const [contextValue, setContextValue] = useState({a: 1, b: 2});
return (
<MyContext.Provider value={contextValue}>
<SomeLargeComponentTree />
</MyContext.Provider>
)
}
function ChildComponent() {
const {a} = useContext(MyContext);
return <div>{a}</div>
}
If the ProviderComponent were to then call setContextValue({a: 1, b: 3}), the ChildComponent would re-render, even though it only cares about the a field based on destructuring. It also doesn't matter how many levels of hooks are wrapping that useContext(MyContext) call. A new reference was passed into the provider, so all consumers will re-render. In fact, if I were to explicitly re-render with <MyContext.Provider value={{a: 1, b: 2}}>, ChildComponent would still re-render because a new object reference has been passed into the provider! (Note that this is why you should never pass object literals directly into context providers, but rather either keep the data in state or memoize the creation of the context value.)
For React-Redux: yes, it uses context internally, but only to pass the Redux store instance down to child components - it doesn't pass the store state using context!. If you look at the actual implementation, it's roughly this but with more complexity:
function useSelector(selector) {
const [, forceRender] = useReducer( counter => counter + 1, 0);
const {store} = useContext(ReactReduxContext);
const selectedValueRef = useRef(selector(store.getState()));
useLayoutEffect(() => {
const unsubscribe = store.subscribe(() => {
const storeState = store.getState();
const latestSelectedValue = selector(storeState);
if(latestSelectedValue !== selectedValueRef.current) {
selectedValueRef.current = latestSelectedValue;
forceRender();
}
})
return unsubscribe;
}, [store])
return selectedValueRef.current;
}
So, React-Redux only uses context to pass the store itself down, and then uses store.subscribe() to be notified when the store state has changed. This results in very different performance behavior than using context to pass data.
There was an extensive discussion of context behavior in React issue #14110: Provide more ways to bail out of hooks. In that thread, Sebastian Markbage specifically said:
My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It's also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It's not ready to be used as a replacement for all Flux-like state propagation.
In fact, we did try to pass the store state in context in React-Redux v6, and it turned out to be insufficiently performant for our needs, which is why we had to rewrite the internal implementation to use direct subscriptions again in React-Redux v7.
For complete detail on how React-Redux actually works, read my post The History and Implementation of React-Redux, which covers the changes to the internal implementation over time, and how we actually use context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75498437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ThreadPoolTaskExecutor giving ConnectionPoolTimeOutException Getting this error even though the total count of active thread is less than the corepoolsize.
ThreadPool which I have created :
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1500);
executor.setMaxPoolSize(2000);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("MakeShoppingRequest");
executor.setKeepAliveSeconds(10);
executor.setAllowCoreThreadTimeOut(true);
executor.initialize();
Exception:
**org.springframework.ws.client.WebServiceIOException: I/O error: Timeout waiting for connection from pool; nested exception is org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool**
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
at jdk.internal.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:316)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:282)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
at org.springframework.ws.transport.http.ClientHttpRequestConnection.onSendAfterWrite(ClientHttpRequestConnection.java:83)
at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:48)
at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:658)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:606)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
... 15 more
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66383729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it necessary to hash REST API tokens? So I have a REST API and some socket APIs which use a common token validation module. Here are the things that the token module does:
function tokenManager() {
this.generate = (db, userId, cacheManager) => {
/*Generates a token for a user and stores it in a db, also puts it in a cache as token: userId key-
value pair.*/
}
this.verify = async (db, token, cacheManager) => {
/*Checks the cache if a user is present for the given token and returns the user id. If the token was
not found in cache, it verifies it from database and puts it in cache.*/
//Each time for a successful verification, the token validity is increased by one day.
}
}
This approach works well, however the tokens are stored in database as plain text. If someone gains access to the database they could get the tokens and make API calls, although rate limiting is present, there is some data compromised. I was planning to hash the API tokens and store them, but a hash compare has to be done on literally every request putting extra computation load on server. (especially bad for node). Is there a better way to implement this? Or is it even necessary to hash API tokens?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64403682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Firebase ML Kit Simple Audio Recognition "Failed to create a TFLite interpreter for the given model" I have been trying to implement the Simple Audio Recognition Tensorflow sample in iOS using the Firebase's ML kit. I have successfully trained the model and converted it into a TFlite file. The model takes the Audio(wav) file path as input([String]) and gives the predictions as output(float32). My iOS code is fairly simple
func initMLModel(){
/*Initializing local TFLite model*/
guard let modelPath = Bundle.main.path(forResource: "converted_model", ofType: "tflite") else {
return
}
let myLocalModel = LocalModelSource.init(modelName: "My", path: modelPath)
let registrationSuccessful = ModelManager.modelManager().register(myLocalModel)
let options = ModelOptions(cloudModelName: nil, localModelName: "My")
let interpreter = ModelInterpreter.modelInterpreter(options: options)
let ioOptions = ModelInputOutputOptions()
do {
try ioOptions.setInputFormat(index: 0, type: .unknown, dimensions: []) /*input is string path. Since string is not defined, setting it as unknown.*/
try ioOptions.setOutputFormat(index: 0, type: .float32, dimensions: [1,38]) /* output is 1 of 38 labelled classes*/
} catch let error as NSError {
print("Failed to set IO \(error.debugDescription)")
}
let inputs = ModelInputs()
var audioData = Data()
let audiopath = Bundle.main.path(forResource: "audio", ofType: "wav")
do {
audioData = try Data.init(contentsOf: URL.init(fileURLWithPath: audiopath!))
//try inputs.addInput(audioData) /*If the input type is direct audio data*/
try inputs.addInput([audiopath])
} catch let error as NSError {
print("Cannot get audio file data \(error.debugDescription)")
return
}
interpreter.run(inputs: inputs, options: ioOptions) { (outputs, error) in
if error != nil {
print("Error running the model \(error.debugDescription)")
return
}
do {
let output = try outputs!.output(index: 0) as? [[NSNumber]]
let probabilities = output?[0]
guard let labelsPath = Bundle.main.path(forResource: "conv_labels", ofType: "txt") else { return }
let fileContents = try? String.init(contentsOf: URL.init(fileURLWithPath: labelsPath))
guard let labels = fileContents?.components(separatedBy: "\n") else {return}
for i in 0 ..< labels.count {
if let probability = probabilities?[i] {
print("\(labels[i]) : \(probability)")
}
}
}catch let error as NSError {
print("Error in parsing the Output \(error.debugDescription)")
return
}
}
}
But when i run this i get the following error output Failed to create a TFLite interpreter for the given model. The Complete Log of the sample app is as below
2019-01-07 18:22:31.447917+0530 sample_core_ML[67500:3515789] - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
2019-01-07 18:22:33.354449+0530 sample_core_ML[67500:3515686] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2019-01-07 18:22:34.789665+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023007] Analytics v.50400000 started
2019-01-07 18:22:34.790814+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )
2019-01-07 18:22:35.542993+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
2019-01-07 18:22:35.543205+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
2019-01-07 18:22:35.543923+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
2019-01-07 18:22:35.544070+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
2019-01-07 18:22:39.981492+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
2019-01-07 18:22:39.981686+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
Failed to set IO Error Domain=com.firebase.ml Code=3 "input format 0 has invalid nil or empty dimensions." UserInfo={NSLocalizedDescription=input format 0 has invalid nil or empty dimensions.}
2019-01-07 18:22:40.604961+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
2019-01-07 18:22:40.605199+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
Error running the model Optional(Error Domain=com.firebase.ml Code=2 "Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite)." UserInfo={NSLocalizedDescription=Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite).})
When looked at this line Didn't find custom op for name 'DecodeWav' I looked up on the custom supported ops and found that Tensorflow already supports this in the audio_ops.cc by default.
Details
My Tensorflow Version : 1.12.0
Environment : Conda
OS Version : Mac OSX Mojave 10.14.2
Deployment target : ios 12.0
Installation type : Pod Installation (pod 'Firebase/MLModelInterpreter')
But i ran my training model first in v1.9.0. Then updated the Tensorflow to latest v1.12.0 to run the TFLite Convertor. Both are master branch.
My TFLite Convertor code Python
import tensorflow as tf
graph_def_file = "my_frozen_graph.pb"
input_arrays = ["wav_data"]
output_arrays = ["labels_softmax"]
input_shape = {"wav_data" : [1,99,40,1]}
converter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(
graph_def_file, input_arrays, output_arrays, input_shape)
converter.allow_custom_ops = True
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
A: I posted this same question in the firebase quickstart iOS repository, And i got the following response DecodeWav op is never supported by TensorFlowLite. So at present Tensorflow Lite does not support audio processing even-though Tensorflow itself supports audio processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54093248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML link with GET parameters: load page html and javascript before executing ajax request When I paste the HTML link below in my address bar or press the browser "previous page" button my ajax GET request is executed before the html content is fully loaded resulting in my ajax returned content being displayed above my nav bar and therefore breaking my site.
If the same request gets executed from within the site then everything is fine.
How can I make sure the page HTML and javascript loads before the ajax request is fired?
EDIT: SOLVED (answer in post below)
HTML LINK
https://domainName/?action=listy&p=test
JS pushstate
var container = document.querySelector('.lnk');
var url = "";
container.addEventListener('click', function(e) {
if (e.target != e.currentTarget) {
e.preventDefault();
if (e.target.getAttribute('name')) {
var data = e.target.getAttribute('name')
url = "?action=list&p=" + data;
history.pushState(data, null, url);
}
}
e.stopPropagation();
}, false);
window.addEventListener('popstate', function(e) {
window.location.replace(url);
});
JQuery AJAX
$(document).ready(function() {
// .....
success: function(dataBack) {
$('.content-area').html(dataBack);
},
});
PHP
if(isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
$var = $_GET['p'];
switch($action) {
case 'list' : list($var);break;
}
}
A: This works for me (Note this uses the jquery library):
$(document).ready(function () {
Your code here...
});
This will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this:
setTimeout(function () {
Your code here...
}, 1000);
It waits a specific amount of milliseconds before executing the function.
A: Turns out the issue was coming from my index.php structure;
I moved the php code in separate files and included it at the end of index.php instead of the top.
Now Im having other issues but the main question is resolved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47904530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get random ID from DB on button click Hi guys (I'm a beginner so take it easy) I have this code which searches my database and brings up the title / artists and that works fine. I am required to make a button which when clicked it brings up a random ID from my database. I have looked around but can't find anything useful.Trying to come up with a lamda expression or something...
Thanks
CONTROLLER
public ActionResult Play(string searchTitle, string searchArtist, string shuffle)
{
var media = from s in db.UploadTables select s;
if (!string.IsNullOrEmpty(searchTitle))
{
media = media.Where(m => m.MediaTitle.Contains(searchTitle));
}
if (!string.IsNullOrEmpty(searchArtist))
{
media = media.Where(m => m.MediaArtist.Contains(searchArtist));
}
return View(media);
}
VIEW
@using (Html.BeginForm())
{
<p>
Song Name: @Html.TextBox("searchTitle")
<input type="submit" value="Search" />
Artist: @Html.TextBox("searchArtist")
<input type="submit" value="Search" />
@Html.TextBox("shuffle")
<input type="submit" value="Search" />
</p>
<hr />
}
A: Random rand = new Random();
int total = db.UploadTables.Count();
var randomId = db.UploadTables.Skip(rand.Next(total)).First().Id;
Random.Next(Int32 maxValue) will get a number between 0 and maxValue-1.
IQueryable<TSource>.Skip(this IQueryable<TSource>, int count) will skip count entries.
You then take the First() of the remaining entries and tadaa you can access its Id field.
Obviously, this is only one way to do it, and as told by others, there are many ways to do that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51824399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to develop apps for iOS with iPod? I develop games for Android, but now I want to try the iOS platform. Actually, I have Mac Mini, but I haven't enought money to buy iPhone, so I think about buying iPod Touch instead. Is it possible to develop games (Unity engine) using iPod? What about games performance? Sorry if I ask something stupid, I never developed for iOS before, thanks!
A: We use an iTouch for development (cheaper than buying iPad2's). So yes, you can definitely develop for iOS using an iTouch/iPod.
You will also need to join the Apple developer program before you can deploy to the iTouch - Apple has a $99 annual fee for an individual. Even if you purchase Unity you will need buy into the Apple dev program too.
A: same code will work in iphone,ipad ,ipod .so no problem.so that the name of IDE is xcode.but performance and image accuracy will be varied.
http://unity3d.com/company/news/iphone-press.html
A: Apple provides a SDK including a simulator. Never trust the simulator completely, but you can use it easily for day by day job, and test it on a real iphone, ipod touch or similar only from time to time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6746559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django tagging migration to GAE I have a Django app that use a django-tagging. I need to port this application to GAE. So, the main problem is to migrate tagging part. It has a complicated model, that should be rewritten to work with Google store. I think tagging is very popular django app and someone has the same problem before. Has someone a rewritten model?
A: Check Nick's post about tagging blog posts. It covers all main tagging issues.
A: There is a modified django-tagging, probably it might work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1643838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add delay between jquery steps transition (jquery steps plugin) I am using http://www.jquery-steps.com/Examples#advanced-form plugin.
How can I add delay between the two steps?
I have tried adding the timeout function in onStepChanging and onStepChanged but it's not working.
Here's what my code looks like:
var form = $("#example-advanced-form").show();
form.steps({
headerTag: "h3",
bodyTag: "fieldset",
transitionEffect: "slideLeft",
onStepChanging: function (event, currentIndex, newIndex)
{
// Allways allow previous action even if the current form is not valid!
if (currentIndex > newIndex)
{
return true;
}
// Forbid next action on "Warning" step if the user is to young
if (newIndex === 3 && Number($("#age-2").val()) < 18)
{
return false;
}
// Needed in some cases if the user went back (clean up)
if (currentIndex < newIndex)
{
// To remove error styles
form.find(".body:eq(" + newIndex + ") label.error").remove();
form.find(".body:eq(" + newIndex + ") .error").removeClass("error");
}
form.validate().settings.ignore = ":disabled,:hidden";
return form.valid();
},
onStepChanged: function (event, currentIndex, priorIndex)
{
// Used to skip the "Warning" step if the user is old enough.
if (currentIndex === 2 && Number($("#age-2").val()) >= 18)
{
form.steps("next");
}
// Used to skip the "Warning" step if the user is old enough and wants to the previous step.
if (currentIndex === 2 && priorIndex === 3)
{
form.steps("previous");
}
},
onFinishing: function (event, currentIndex)
{
form.validate().settings.ignore = ":disabled";
return form.valid();
},
onFinished: function (event, currentIndex)
{
alert("Submitted!");
}
}).validate({
errorPlacement: function errorPlacement(error, element) { element.before(error); },
rules: {
confirm: {
equalTo: "#password-2"
}
}
});
A: how about this
setTimeout(function(){ /*your function*/ }, 3000);
https://www.w3schools.com/JSREF/met_win_setTimeout.asp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45648661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Reflection to determine which Fields are backing fields of a Property I'm using reflection to map out objects. These objects are in managed code but I have no visibility into their source code, underlying structure, etc. other than through reflection. The overarching goal of all this is a rudimentary memory map of an object (similar in functionality to SOS.dll DumpObject and !ObjSize commands). As such, I'm trying to determine which members are being "double counted" as both a field and a property.
For example:
public class CalendarEntry
{
// private property
private DateTime date { get; set;}
// public field
public string day = "DAY";
}
When mapped shows:
*
*Fields
*
*day
*k__BackingField
*Properties
*
*date
Where as a class like this:
public class CalendarEntry
{
// private field
private DateTime date;
// public field
public string day = "DAY";
// Public property exposes date field safely.
public DateTime Date
{
get
{
return date;
}
set
{
date = value;
}
}
}
When mapped shows:
*
*Fields
*
*day
*date
*Properties
*
*Date
At first glance there's nothing to tell you that the Date property's "backing field" is the field named date. I'm trying to avoid counting date twice in this scenario since that will give me a bad memory size approximation.
What's more confusing/complicated is I've come across scenarios where properties don't always have a corresponding field that will be listed through the Type.GetFields() method so I can't just ignore all properties completely.
Any ideas on how to determine if a field in the collection returned from Type.GetFields() is essentially the backing field of some corresponding property returned from Type.GetProperties()?
Edit- I've had trouble determining what conditions a property will not have a corresponding field in listed in the collection returned from Type.GetFields(). Is anyone familiar with such conditions?
Edit 2- I found a good example of when a property's backing field would not be included in the collection returned from Type.GetFields(). When looking under the hood of a String you have the following:
*
*Object contains Property named FirstChar
*Object contains Property named Chars
*Object contains Property named Length
*Object contains Field named m_stringLength
*Object contains Field named m_firstChar
*Object contains Field named Empty
*Object contains Field named TrimHead
*Object contains Field named TrimTail
*Object contains Field named TrimBoth
*Object contains Field named charPtrAlignConst
*Object contains Field named alignConst
The m_firstChar and m_stringLength are the backing fields of the Properties FirstChar and Length but the actual contents of the string are held in the Chars property. This is an indexed property that can be indexed to return all the chars in the String but I can't find a corresponding field that holds the characters of a string. Any thoughts on why that is? Or how to get the backing field of the indexed property?
A: The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern.
I think you've already hit on the answer to your question: ignore all properties.
Remember that a property is just one or two functions in disguise. A property will only have a compiler generated backing field when specifically requested by the source code. For example, in C#:
public string Foo { get; set; }
But the creator of a class need not use compiler generated properties like this. For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on. In these cases, you wouldn't expect to see a single backing field for each property. It's fine to ignore these properties. Your code won't miss any actual data.
A: You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory.
Also, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code:
private DateTime today;
public DateTime CurrentDay
{
get { return today; }
}
How do you expect to figure out that there is some relation between the today field and the CurrentDay property?
EDIT: Regarding your more recent questions:
If you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code.
Regarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, β¦), you can't find their size by looking at their fields. For all other types, you can.
A: To answer your other question:Under what circumstances do properties not have backing fields?
public DateTime CurrentDay
{
get { return DateTime.Now; }
}
or property may use any other number of backing fields/classes
public string FullName
{
get {return firstName + " " + lastName;}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14322660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Line below link on hover How can I add a short line below link ? The line should be visible only on hover.
I tried with border-bottom, but that way the line is 100% of the link width and I want the line to be shorter than the link .
Here is a example image of the effect that I try to make.
A: This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).
HTML:
<div>Test</div>
CSS:
div {
width: 30px;
}
div:hover:after {
content: "";
display: block;
width: 5px;
border-bottom: 1px solid;
margin: 0 auto;
}
DEMO
Updated CSS:
div {
display: inline-block;
}
Not sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.
DEMO HERE
Here is a link using the same method, just incase you got confused.
DEMO HERE
So I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.
width: 70%;
Changed the width from 5px to 70% so it will expand with the width of the text.
DEMO HERE
A: Edit:
Ruddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:
a {
display: inline-block;
text-decoration:none
}
a:after {
content: "";
display: block;
width: 0;
border-bottom: 1px solid;
margin: 0 auto;
transition:all 0.3s linear 0s;
}
a:hover:after {
width: 90%;
}
jsfiddle link
(Original answer below)
Check this i just came up with, playing in the fiddle:
<a class="bordered" href="#">I am a link, hover to see</a>
a.bordered {
text-decoration:none;
position: relative;
z-index : 1;
display:inline-block;
}
a.bordered:hover:before {
content : "";
position: absolute;
left : 50%;
bottom : 0;
height : 1px;
width : 80%;
border-bottom:1px solid grey;
margin-left:-40%;
}
Depending on the percentages, you may play with a.bordered:hover:before margin and left position.
A: Simply use this class:
.link:hover {
background-image:url("YOUR-SMALL-LINE-BOTTOM.png")
}
like this, the line will appear when you hover over the element. And you can specify in the image, how small or big the line has to be.
A: Try creating another Div for border. And adjust the width of that div according to your choice. I hope this will help.
A: what about this?
a {text-decoration:none;position:relative;}
a:hover:before {content:"_";position:absolute;bottom:-5px;left:50%;width:10px;margin:0 0 0 -5px;}
check this fiddle for more: http://jsfiddle.net/h7Xb5/
A: You can try using ::after pseudo element:
a {
position: relative;
text-decoration: none;
}
a:hover::after {
content: "";
position: absolute;
left: 25%;
right: 25%;
bottom: 0;
border: 1px solid black;
}
<a href='#'>Demo Link</a>
A: use underline or if u want the line to be much shorter try scalar vector graphics(svg) with this you can have custom lines.
<svg id="line "height="40" width="40">
<line x1="0" y1="0" x2="700" y2="20" style="stroke:rgb(125,0,0);stroke-width:2" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23631822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: EF Insert Array into db With View I have something to ask , i 'm going to create a simple application that store value of student Below is my class which i have tried .
Class Data{
public int Id {get;set;}
public string Name {get;set;}
public int[] ValuesStudent{get;set;}
}
And below is example of the data
id = 1
Name = Jhon
Values = 9,8,7,5,9,7,4,6,4
id = 2
Name = Uncle
Values = 4,7,8,4
id = 3
Name = Jhon
Values = 9,8,7,5,9,7
as you can see above example of the data i can insert multiple value as i need, Student has taken 3 examination so i must insert 3 values for him .
But what i'm confuse is how can i make insert new Data . enter image description here
Oke if you any link which refer about problem , and explain about it , you can directly comment it .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39550765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a property I can check to see if code is rendered using hydrate vs render? I have a React app (with SSR) and need to handle things differently for server vs browser renders.
A: I ended up using the following, but my gut feeling is there is a better way.
if (typeof window !== "undefined") {
// This code is rendered in browser vs server
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64279861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to abort processing a request in NodeJS http server I have your standard callback-hell http server like (simplified):
http.createServer((req, res) => {
doSomething(() => {
doMoreSomethings(() => {
if (!isIt())
// explode A
if (!isItReally())
// explode B
req.on('data', (c) => {
if (bad(c))
// explode C
});
req.on('end', () => {
// explode D
});
});
});
};
The only way I know of to end the request is res.end(), which is asynchronous, so stuff after you call that will run (as far as I can tell). Is there a way to do a pseudo-process.exit mid-flight and abort processing the request, so I don't waste time on other stuff? For example how can I stop at the above // explode lines and not process anything else? throw doesn't leap over scope boundaries. Basically, I think, I want to return or break out of the createServer callback from within a nested callback. Is the only way to do this to be able to have code with a single path and just not have more than one statement at each step? Like, horizontal coding, instead of vertical KLOCs.
I'm a Node noob obviously.
Edit: Maybe another way to ask the question is: Is it possible to abort at the // explode C line, not read any more data, not process the end event, and not process any more lines in the doMoreSomethings callback (if there were any)? I'm guessing the latter isn't possible, because as far as I know, doMoreSomethings runs to completion, including attaching the data and end event handlers, and only then will the next event in the queue (probably a data event) get processed, at which point doMoreSomethings is done. But I am probably missing something. Does this code just zip through, call isIt and isItReally, assign the event handlers, hop out of all the callbacks, the createServer callback finishes, and then all the extra stuff (data/end/etc.) runs from the event queue?
A: Typically you will use a return statement. When you call return any code below it will not get executed. Although, if your functions isIt() or isItReally() are asynchronous functions then you will be running into trouble as those are used in a synchronous fashion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40808578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Looking for a script/tool to dump a list of installed features and programs on Windows Server 2008 R2 The same compiled .Net / C++ / Com program does different things on two seemingly same computers. Both have DOZENS of things installed on them. I would like to figure out what the difference between the two is by looking at an ASCII diff. Before that I need to "serialize" the list of installed things in a plain readable format - sorted alphabetically + one item per line.
A Python script would be ideal, but I also have Perl, PowerShell installed.
Thank you.
A: You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
If this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access.
A: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit.
Also, there is Microsoft Support article How to Use WinDiff to Compare Registry Files.
For a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for example).
A: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install)
There is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote).
You can also run it live from here, so though not strictly pythonic you could plug it in quite nicely.
A: Taken from List installed software from the command line:
If you want to list the software known to Windows Management
Instrumentation (WMI) from the command line, use WMI command line
(WMIC) interface.
To list all products installed locally, run the following
command:
wmic product
Caveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2448612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Python CGI for a big HTML file I have a big html file named exercise.html, I need generate to one som stuff by Python CGI.
I want to ask you what is the best way to print this HTML.
I know that it is possible by print method with using format methods %s, %i etc.:
print '''<html>
<head><title>My first Python CGI app</title></head>
<body>
<p>Hello, 'world'!</p>
.
.
<div>%s</div>
.
.
</body>
</html>''' % generated_text
But this HTML is really big,so is this only one solution?
A: You should consider using a templating language like Jinja2.
Here is a simple example straight from the link above:
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')
Generally, though you save templates in a file, and then load / process them:
from jinja2 import Environment, PackageLoader
# The env object below finds templates that are lcated in the `templates`
# directory of your `yourapplication` package.
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
As demonstrated above, templates let you put variables into the template. Placing text inside {{ }} makes it a template variable. When you render the template, pass in the variable value with a keyword argument. For instance, the template below has a name variable that we pass via template.render
This is my {{name}}.
template.render(name='Jaime')
A: Also consider Python Bottle (SimpleTemplate Engine). It is worth noting that bottle.py supports mako, jinja2 and cheetah templates.
The % indicates python code and the {{var}} are the substitution variables
HTML:
<ul>
% for item in basket:
<li>{{item}}</li>
% end
</ul>
Python:
with open('index.html', 'r') as htmlFile:
return bottle.template(htmlFile.read(), basket=['item1', 'item2'])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23654230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Callback parameters gets shifted I have a video c++ callback function where the parameters get suddently shifted after a few hours. In debug, it will assert on this:
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
{
assert(nWidth < 4000);
CCameraInstance *pThis = (CCameraInstance*)pContext;
pThis->PaintFrame(pBuffer, nWidth, nHeight, nFrameErrorNo);
}
When the debugger breaks on the assert, nWidth has a big invalid value. However, nHeight is 320 (the width value) and nFrameErrorNo is 240 (the nHeight value).
How can the parameters get shift that way?
A: The shift could be caused by the hidden this pointer. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
From the code you have pasted here
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
I can see the callback function is a member of class CCameraInstance
I'm not sure whether you are defining the function as a static function or a normal one. But in theory it should be a static function to avoid the this pointer. Using a C++ class member function as a C callback function
However, I had a problem with C++/CLI even if i have define the member function as static. The this pointer/Handle still exist.
I think you can try to define your function as
void CCameraInstance::VideoCallback(CCameraInstance* test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
and have try.
If you are using C++/CLI it would be
void CCameraInstance::VideoCallback(CCameraInstance^ test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19498545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Composite/Combined Indexing vs Single Index vs multiple Combined Indexed on a large table I have a very large table (that is still growing) (around 90GB with ~350mil rows). It is a table that include sales of items, if you were wondering.
In this table, there's (for example), column A,B,C,D,E,F,G.
Currently, I am using a combined index, consisting of (A,B,C,D,E,F).
Usually, the query will consist of A,B,C,D,E. F is included occasionally (hence the indexing).
eg,
SELECT * FROM table WHERE A = ? AND B = ? AND C = ? AND D = ? AND E = ?;
Sometimes, with the addon of AND F = ?;
But on certain occasion, the query will consist of A,B,C,D,G (whereby G is not indexed (not combined nor single indexed).
This causes timeout on certain occasion as the data is quite big.
So my question is, in order to solve this issue in terms of indexing,
should I
Option 1: add G into the combined index, making it become (A,B,C,D,E,F,G).
*
*Does this even work when I query A,B,C,D,G (missing E & F)?
Option 2: add G as a single index.
*
*Based on what i know, this does not work, as my query has A,B,C,D,G. The first combined index will be used instead (correct me if I'm wrong).
Option 3: Go with option 1, combine all the columns, but I change my query instead, to always query A,B,C,D,E,F,G even when F is not needed.
eg,
SELECT * FROM table WHERE A = ? AND B = ? AND C = ? AND D = ? AND E = ? AND F IS NOT NULL AND G = ?;
Thanks
A: Option 1 - Yes, this will work. The server will perform index seek by (A,B,C,D,E) and furter index scan by (G).
Option 2 - Makes no sense in most cases, server uses only one index for one source table copy. But when the selectivity of single index by (G) is higher than one for (A,B,C,D,E) combination then the server will use this single-column index.
Option 3 - The processing is equal to one in Option 2.
A: Are the PRIMARY KEY's column(s) included in A..E ? If so, none of the indexes are needed.
What datatypes are involved?
Are they all really tests on =? If not then 'all bets are off'. More specifically, useful indexes necessarily start with the columns tested with = (in any order). In particular, F IS NOT NULL is not = (but IS NULL would count as =).
I would expect INDEX(A,B,C,D,E, anything else or nothing else) to work for all of the queries you listed. (Hence, I suspect there are some details missing from your over-simplified description.)
How "selective" are F and G? For example, if most of the values of G are distinct, then INDEX(G) would possibly be useful by itself.
Please provide SHOW CREATE TABLE and EXPLAIN SELECT ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73581169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to convert below javascript code to work in IE11 I want to convert my code from es6 to es4-3 so that it supports IE11. I am trying to toggle the class="open" for the three button which helps me to open a small div.
JS:
let customSelect = document.getElementsByClassName('input-select')
Array.from(customSelect).forEach((element, index) => {
element.addEventListener('click', function () {
Array.from(customSelect).forEach((element, index2) => {
if (index2 !== index) {
element.classList.remove('open')
}
})
this.classList.add('open')
})
for (const option of document.querySelectorAll('.select-option')) {
option.addEventListener('click', function () {
if (!this.classList.contains('selected')) {
this.parentNode
.querySelector('.select-option.selected')
.classList.remove('selected')
this.classList.add('selected')
this.closest('.input-select').querySelector(
'.input-select__trigger span'
).textContent = this.textContent
}
})
}
// click away listener for Select
document.addEventListener('click', function (e) {
var isClickInside = element.contains(e.target);
if(!isClickInside) {
element.classList.remove('open');
}
return
})
})
HTML:
<div class="input-select">
<button></button>
<div class="select-options">
<h1>Hi</h1>
<h1>Bye</h1>
</div>
</div>
<div class="input-select">
<button></button>
<div class="select-options">
<h1>Hi</h1>
<h1>Bye</h1>
</div>
</div><div class="input-select">
<button></button>
<div class="select-options">
<h1>Hi</h1>
<h1>Bye</h1>
</div>
</div>
This is pure es6 code i need to convert it into lower version of js
A: This is the Babel's (targeted only to IE 11) answer:
"use strict";
function _createForOfIteratorHelper(o, allowArrayLike) {
var it =
(typeof Symbol !== "undefined" && o[Symbol.iterator]) || o["@@iterator"];
if (!it) {
if (
Array.isArray(o) ||
(it = _unsupportedIterableToArray(o)) ||
(allowArrayLike && o && typeof o.length === "number")
) {
if (it) o = it;
var i = 0;
var F = function F() {};
return {
s: F,
n: function n() {
if (i >= o.length) return { done: true };
return { done: false, value: o[i++] };
},
e: function e(_e) {
throw _e;
},
f: F
};
}
throw new TypeError(
"Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
);
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function s() {
it = it.call(o);
},
n: function n() {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function e(_e2) {
didErr = true;
err = _e2;
},
f: function f() {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
var customSelect = document.getElementsByClassName("input-select");
Array.from(customSelect).forEach(function (element, index) {
element.addEventListener("click", function () {
Array.from(customSelect).forEach(function (element, index2) {
if (index2 !== index) {
element.classList.remove("open");
}
});
this.classList.add("open");
});
var _iterator = _createForOfIteratorHelper(
document.querySelectorAll(".select-option")
),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done; ) {
var option = _step.value;
option.addEventListener("click", function () {
if (!this.classList.contains("selected")) {
this.parentNode
.querySelector(".select-option.selected")
.classList.remove("selected");
this.classList.add("selected");
this.closest(".input-select").querySelector(
".input-select__trigger span"
).textContent = this.textContent;
}
});
} // click away listener for Select
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
document.addEventListener("click", function (e) {
var isClickInside = element.contains(e.target);
if (!isClickInside) {
element.classList.remove("open");
}
return;
});
});
A: You can use Babel to transpile the code first. You can also refer to this tutorial about how to use Babel to transpile code.
The code I use Babel to transpile is like below:
'use strict';
var customSelect = document.getElementsByClassName('input-select');
Array.from(customSelect).forEach(function (element, index) {
element.addEventListener('click', function () {
Array.from(customSelect).forEach(function (element, index2) {
if (index2 !== index) {
element.classList.remove('open');
}
});
this.classList.add('open');
});
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = document.querySelectorAll('.select-option')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var option = _step.value;
option.addEventListener('click', function () {
if (!this.classList.contains('selected')) {
this.parentNode.querySelector('.select-option.selected').classList.remove('selected');
this.classList.add('selected');
this.closest('.input-select').querySelector('.input-select__trigger span').textContent = this.textContent;
}
});
}
// click away listener for Select
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
document.addEventListener('click', function (e) {
var isClickInside = element.contains(e.target);
if (!isClickInside) {
element.classList.remove('open');
}
return;
});
});
Then add this line of code before the script to add a polyfill:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71392000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FileNotFoundException : Could not open ServletContext resource [/WEB-INF/spring/root-context.xml] I am facing below exception while building a SpringMVC application through Maven.
Maven builds the application and tries to deploy on already running tomcat which fails.
If I build and run the same code through eclipse+inbuild Tomcat, it runs fine.
Exception coming while building from Maven:
java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1095)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1930)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]
at
web.xml
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<!-- this context-param is needed otherwise app will look for /WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Here is my project Structure
Is there any way to solve this ?
Thanks
A: @ian-roberts and @bohuslav-burghardt already answered your question: you have created a structure that doesn't conform to the structure that Maven project must have.
To fix it you should put all contents of WebContent directory to src/main/webapp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32652133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In python, is it easy to call a function multiple times using threads? Say I have a simple function, it connects to a database (or a queue), gets a url that hasn't been visited, and then fetches the HTML at the given URL.
Now this process is serial, i.e. it will only fetch the html from a given url one at a time, how can I make this faster by doing this in a group of threads?
A: Yes. Many of the Python threading examples are just about this idea, since it's a good use for the threads.
Just to pick the top four Goggle hits on "python threads url": 1, 2, 3, 4.
Basically, things that are I/O limited are good candidates for threading speed-ups in Python; things the are processing limited usually need a different tool (such as multiprocessing).
A: You can do this using any of:
*
*the thread module (if your task is a function)
*the threading module (if you want to write your task as a subclass of threading.Thread)
*the multiprocessing module (which uses a similar interface to threading)
All of these are available in the Python standard library (2.6 and later), and you can get the multiprocessing module for earlier versions as well (it just wasn't packaged with Python yet).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4962022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: password set during checkout issue I have an issue with customer registered through checkout.
After the checkout process, the customer lands in βMy Accountβ but once logged off, he canβt acces "My Account" anymore, the message "Invalid login or password" is displayed.
Setting a new password through βForgotten Passwordβ button seems to solve the problem for the customer. (But it would be great if the password could work directly without passing through this step.)
I think (but am not sure at all) that the password set through billing.phtml is not stored correctly.
The customers registered through "Register" button are saved correctly and don't encounter any issue.
I have in template/persistent/Customer/form/register.phtml:
<li class="fields">
<div class="field">
<label for="password" class="required"><em>*</em><?php echo $this->__('Password') ?></label>
<div class="input-box">
<input type="password" name="password" id="password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />
</div>
</div>
<div class="field">
<label for="confirmation" class="required"><em>*</em><?php echo $this->__('Confirm Password') ?></label>
<div class="input-box">
<input type="password" name="confirmation" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="confirmation" class="input-text required-entry validate-cpassword" />
</div>
</div>
</li>
In template/Customer/form/resetforgottenpassword.phtml:
<li class="fields">
<div class="field">
<label for="password" class="required"><em>*</em><?php echo $this->__('New Password'); ?></label>
<div class="input-box">
<input type="password" class="input-text required-entry validate-password" name="password" id="password" />
</div>
</div>
<div class="field">
<label for="confirmation" class="required"><em>*</em><?php echo $this->__('Confirm New Password'); ?></label>
<div class="input-box">
<input type="password" class="input-text required-entry validate-cpassword" name="confirmation" id="confirmation" />
</div>
</div>
</li>
And in template/persistent/checkout/onepage/billing.phtml, which I think is the culprit:
<li class="fields" id="register-customer-password">
<div class="field">
<label for="billing:customer_password" class="required"><em>*</em><?php echo $this->__('Password') ?></label>
<div class="input-box">
<input type="password" name="billing[customer_password]" id="billing:customer_password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />
</div>
</div>
<div class="field">
<label for="billing:confirm_password" class="required"><em>*</em><?php echo $this->__('Confirm Password') ?></label>
<div class="input-box">
<input type="password" name="billing[confirm_password]" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="billing:confirm_password" class="input-text required-entry validate-cpassword" />
</div>
</div>
</li>
I tried several modifications to billing.phtml, such as:
<label for="password" class="required"><em>*</em><?php echo $this->__('Password') ?></label>
<input type="password" name="password" id="password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />
<input type="password" name="password" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="confirmation" class="input-text required-entry validate-cpassword" />
But Iβm still leading to the same result.
Iβm on a CE 1.9.3.1 patched with SUPEE 9652.
How to make Customer registered during checkout being saved correctly?
A: I have 4 errors concerning lib/Varien/Crypt/Mcrypt.php
Warning: mcrypt_generic_init(): Key size is 0 in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_init(): Key length incorrect in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_deinit(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 135
Warning: mcrypt_module_close(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 136
I thought it was relative to a module is missing in PHP Mcrypt on my server (https://magento.stackexchange.com/a/35888). But it's not the case as by installing a fresh CE 1.9.3.1 in a folder in the root of the same Magento installation is doing its job properly with the same server configuration and Mcrypt.php. Moreover, the password set during registration with form (?and using the same encryption?), is set properly.
I'll open a new post with more precisions.
@urfusion, thank you for advice, I was looking at the wrong end of system.log (thought it was writing on the top...)
Edit
I got it, the solution's here:
https://stackoverflow.com/a/42474835/7553582
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42439888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change part of window content upon combo box selection changed event? In my wpf window I want to change part of it (make different controls visible) when combo box selection is changed. Exactly like TabControl works, just with combobox. I know I could just make some controls visible while hiding the others in the c# code behind but I want to find out if there are other -better solutions.
A: You can use two Grid or GroupBox (or other container type) controls and put appropriate set of controls in each of them. This way you can just visibility of panels to hide the whole set of controls instead of hiding each control directly.
It may sometimes be appropriate to create a user control for each set of controls. However, this can depend on a specific case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10541331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to block mouse click events from another form I have a winforms single form application that uses a "Thickbox" I've created whenever the loads a new view into the application form.
The "Thickbox" shows another form in front of the application's form that is semi-transparent and has a user control that is the box itself.
This thickbox can be shown a modal dialog and in that case I have no problems at all, but it can also be shown as a non modal, for instance, when the user switches views in the main form, it shows thickbox with a loading animated icon.
The problem is that when the thickbox is shown as non modal, it doesn't block the user from clicking on the buttons of main form of the application.
When thickbox is shown nothing happens, but as soon as it's closed, the click is being processed by the click event handler of the relevant button in the main form.
I can't use ShowDialog since I can't block the UI thread, and I need to get the indication from the main form when to close the thickbox,
I can't set the Enabled property of the owner form as described in this answer (though I've tried various versions of this solution, nothing helps)
I've tried using the win API function BlockInput as descried in this answer, but that didn't block the input,
I think my best chance is using the Application.FilterMessage method, but I couldn't get that to block the mouse clicks as well.
It would be great if I could encapsulate the mouse click blocking inside the thickbox form itself, so that it would be usable easily with other applications as well, but
a solution on to the calling form would also be very much appreciated.
A: I'm glad to announce that the problem is finally solved.
After spending a few days attempting to recreate this bug in a new application, re-constructing the main form in the application, comment out parts of the code in the main application, and generally just shooting all over to try and find a lead, It finally hit me.
The application behaved as if the clicks on the thickbox was queued somehow and only activated when the thickbox was closed. This morning, after fixing some other bugs, The penny finally dropped - all I was missing was a single line of code right before closing the thickbox's form:
Application.DoEvents();
The annoying thing is that it's not something that's new to me, I've used it many times before including in the main application and in the thickbox code itself... I guess I just had to let if go for a while to enable my mind to understand what was so painfully obvious in hindsight...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35684964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Create twin object a.k.a. inheritance clone The working twin(source) function below generates a new object with the same own properties as source and with the same parents (prototype chain). (e.g. twin(isFinite) would be [object Object] and instanceof Function) Does any native function provide the same effect?
/**
* @param {Object|Function} source
* @param {(Object|Function|null)=} parent defaults to source's parents
* @return {Object}
*/
function twin(source, parent) {
var twin, owned, i = arguments.length;
source = i ? source : this; // use self if called w/o args
parent = 2 == i ? parent : Object.getPrototypeOf(source);
twin = Object.create(parent);
owned = Object.getOwnPropertyNames(source);
for (i = owned.length; i--;) {
twin[owned[i]] = source[owned[i]];
}
return twin;
}
Update: A .twin method is available in blood.
A: You can try something like this:
obj= eval(uneval(objSource));
It only works in FF but the idea is to serialize an object and the eval the serialized string instantiating (prototyping) a new object with the same properties as the first one.
You can use also the function JSON.stringify as the "uneval" function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16594717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Updating parent component only after multiple child components have completed running I have a Parent react component with multiple child components that are created through a .map() function. I am passing in a function addCallback() as child props so I have a reference and can trigger all child's handleRun() function via the Parent.
I'm trying to update state of my Parent component to running = true when all children are running and to running = false and render said status on the parent when all children have completed running. However the state doesn't seem to update in the particular sequence I specify.
Here is how I'm doing it:
let promise1 = this.setState({isRunning: true},
() => {
this.state.childRef.map(x => x())
});
Promise.all([promise1])
.then(() => this.setState({isRunning: false}))
Here's the entire code in codesandbox: link
Would appreciate your help as I'm still pretty new to React (and Javascript in general). Thanks!
A: Cause runSomething is not a Promise. You must change.
runSomething() {
return new Promise((resolve, reject) => {
this.setState({ status: "running" });
// simulate running something that takes 8s
setTimeout(() => {
this.setState({ status: "idle" });
resolve(true);
}, 3000);
});
}
A working sandbox here https://codesandbox.io/s/fragrant-cloud-5o2um
A: Using async in a function declaration automatically returns a Promise wrapped around whatever you are returning from your function. In your case, it's undefined. This is why your current code is not throwing any errors at the moment.
You will need a mechanism to wait for the setTimeout. Changing the runSomething function like this will work
async runSomething() {
this.setState({ status: "running" });
// simulate running something that takes 8s
return new Promise(resolve => {
setTimeout(() => {
this.setState({ status: "idle" }, resolve);
}, 3000);
});
}
Do notice the line this.setState({ status: "idle" }, resolve);. It makes sure that your promise resolves not only after the setTimeout but also after the child's state is changed to "idle". Which is the correct indication that your child component has moved to "idle" state.
Codesandbox: https://codesandbox.io/s/epic-boyd-12hkj
A: Here is the sandbox implementation of what you are trying to achieve. Sanbox
Here i have created a state in parent component that will be updated when child is running.
this.state = {
callbacks: [],
components: [
{
index: 0, // we don't need this field its just for your info you can just create [true,false] array and index will represent component index.
status: false
},
{
index: 1,
status: false
}
]
};
When all the status in component array is true we update the idle status of parent to running.
getAllRunningStatus() {
let { components } = this.state;
let checkAllRunning = components.map(element => element.status);
if (checkAllRunning.indexOf(false) === -1) { // you can also use !includes(false)
return true;
}
return false;
}
inside your render function
<h1>Parent {this.getAllRunningStatus() ? "running" : "idle"}</h1>
Note:- I have just written a rough code. You can optimise it as per your requirements. Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56784785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to access a variable that was available when an async method was called? The animal names are fetched from an API that could return 404 if the animal is not found. But in order to properly log the error, we need to have access to the animal's country. Is it possible? I've read something from a guy called Stephen Cleary that made me think it is possible with lambdas, but I couldn't find anything.
var gettingNames = new List<Task<string>>();
foreach (var animal in animals)
{
gettingNames.Add(this.zooApi.GetNameAsync(animal));
}
try
{
await Task.WhenAll(gettingNames);
}
catch (Exception e)
{
var exception = gettingNames.Where(task => task.IsFaulted)
.SelectMany(x => x.Exception.InnerExceptions).First();
this.logger.LogError("The animal name from {Country} was not found",
animal.Country); // This is the goal
}
A: One way to solve this problem is to project each Animal to a Task that contains more information than either a naked name or a naked error. For example you could project it to a Task<ValueTuple<Animal, string, Exception>> that contains three pieces of information: the animal, the animal's scientific name from the zooApi, and the error that may have happened while invoking the zooApi.GetScientificNameAsync method.
The easiest way to do this projection is the LINQ Select operator:
List<Task<(Animal, string, Exception)>> tasks = animals.Select(async animal =>
{
try
{
return (animal, await this.zooApi.GetScientificNameAsync(animal),
(Exception)null);
}
catch (Exception ex)
{
return (animal, null, ex);
}
}).ToList();
(Animal, string, Exception)[] results = await Task.WhenAll(tasks);
foreach (var (animal, scientificName, error) in results)
{
if (error != null)
this.logger.LogError(error,
$"The {animal.Name} from {animal.Country} was not found");
}
A: You have almost nailed it. :)
Rather than having a List<Task<string>> you need a Dictionary<Task<string>, string> structure:
static async Task Main()
{
var taskInputMapping = new Dictionary<Task<string>, string>();
var inputs = new[] { "input", "fault", "error", "test"};
foreach (var input in inputs)
{
taskInputMapping.Add(DelayEcho(input), input);
}
try
{
await Task.WhenAll(taskInputMapping.Keys);
}
catch
{
foreach (var pair in taskInputMapping.Where(t => t.Key.IsFaulted))
{
Console.WriteLine($"{pair.Value}: {pair.Key.Exception?.GetType().Name}");
}
}
}
static readonly ImmutableArray<string> wrongInputs =
ImmutableArray.Create("error", "fault");
static async Task<string> DelayEcho(string input)
{
if (wrongInputs.Contains(input)) throw new ArgumentException();
await Task.Delay(10);
return input;
}
*
*taskInputMapping.Add(DelayEcho(input), input): Stores the input next to the Task itself
*taskInputMapping.Where(t => t.Key.IsFaulted): Iterates through the faulted tasks
*$"{pair.Value}: {pair.Key.Exception?.GetType().Name}": Retrieves the input + the related error
A: I combined the answers and came up with this:
var tasks = animals.Select(async animal =>
{
try
{
return await this.zooApi.GetNameAsync(animal);
}
catch (Exception ex)
{
this.logger.LogError(error,
$"The {animal.Name} from {animal.Country} was not found");
return null;
}
});
var results = await Task.WhenAll(tasks);
foreach (var name in results.Where(x => x != null))...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69383186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HTML divide and conquer i am looking for the best pratice when it comes to HTML.
Now my normal programming instincts tells me to always divide and conquer but i am not sure how or even if it is recommended when it comes to HTML.
So say for example i have the following index file:
<!DOCTYPE html>
<html>
<head>
<title>Dinner plans</title>
</head>
<body>
<div class="header">
<div class="header top">
<ul>
<li>
<div>
<?php
if(isset($_SESSION['loggedin'])){
echo "Du er logged ind";
}else
?>
<input type="text" name="username" id="username"> <input type="password" name="password" id="password">
</div>
</li>
</ul>
</div>
<div class="menu">
<nav>
<ul>
<li>
</li>
</ul>
</nav>
</div>
</div>
</body>
</html>
now i would devide some of this code for example the menu into another HTML file for instance menu.html and then place the content of the file within the index file.
My question is simple is this recommended and if so how is it achieved?
A: I think what you are asking is if you can separate parts of an HTML page into smaller pages, so you can separate concerns.
In PHP this can be accomplished by referencing other files by a require() or include(). But I still don't believe this really answers your question. ASP.NET MVC allows you to render partial views within a webpage through `RenderPartial() but you didn't mention anything about using this.
You can find more at http://www.asp.net/mvc/videos/mvc-2/how-do-i/how-do-i-work-with-data-in-aspnet-mvc-partial-views
A: If you want to divide a single webpage into multiple hmtl files you can do it by inserting frames. This is an old way of programming and you don't really see it these days but its efficient at doing what you are asking.
A: Yes, this is highly recommended. You are trying to apply the DRY principle (see: http://en.wikipedia.org/wiki/Don't_repeat_yourself). It's an excellent idea to apply this to your HTML. You can achieve this using require, require_once, include, and include_once in PHP. If you want to get a bit fancier, take a look at templating systems like Smarty (see: http://www.smarty.net/)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17914717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select ScrollView element (Button) by code I would like to set my scrollView element seleted, using code.
Here is what I have so far (commented code is not working):
public class Dictionary extends Activity implements Runnable, OnClickListener {
//Candidates
candidatesScrollView = (HorizontalScrollView) findViewById(R.id.activity_dictionary_horizontalScrollView1);
candidatesButtons = new ArrayList<Button>();
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button1));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button2));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button3));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button4));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button5));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button6));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button7));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button8));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button9));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button10));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button11));
candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button12));
for(int i = 0; i < candidatesButtons.size(); i++)
((Button) candidatesButtons.get(i)).setOnClickListener(this);
(...)
}
And then in another method:
private void recognize() {
(...)
byte buffer[];
buffer = RecogEngine.setResult(0); // and set the remaining data to engine
try {
candidatesString = new String(buffer, "UTF-8");
for (int i = 0; i < candidatesString.length(); i++)
{
candidatesButtons.get(i).setTextColor(getResources().getColor(R.color.Celadon));
candidatesButtons.get(i).setTypeface(null,Typeface.BOLD);
candidatesButtons.get(i).setText(String.valueOf(candidatesString.charAt(i)));
}
catch (Exception e) {
e.printStackTrace();
}
//HERE_I_WANT_TO_SELECT_AND_HIGHLIGHT (like in default HOLO_DARK THEME)
//candidatesButtons.get(0).requestFocus();
//candidatesButtons.get(0).setSelected(true);
(...)
}
How to do this?
A: I have found the solution for my problem. You should use the following code to set the Button selected:
//HERE THE CODE IS WORKING
candidatesButtons.get(0).requestFocusFromTouch();
candidatesButtons.get(0).setSelected(true);
Maybe it will be useful to someone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17036867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Writing unit tests that work with the DOM I have some functionality that works with the DOM, specifically dealing with resizing elements. I looked over the Unit Testing documentation here and couldn't find anything on doing this. Is it possible? Is there any existing documentation that shows how to do it?
A: Try DumpRenderTree - headless chrome which outputs a textual version of layout.
eg:
Content-Type: text/plain
layer at (0,0) size 808x820
RenderView at (0,0) size 800x600
layer at (0,0) size 800x820
RenderBlock {HTML} at (0,0) size 800x820
RenderBody {BODY} at (8,8) size 784x804
RenderHTMLCanvas {CANVAS} at (0,0) size 800x800 [bgcolor=#808080]
RenderText {#text} at (0,0) size 0x0
#EOF
#EOF
Kevin Moore's blog post "Headless Browser Testing with Dart" explains the details (and the above snippet is taken from that)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14987852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# Object reference not set to an instance of an object. Instantiating Class within a List? public class OrderItem
{
public string ProductName { get; private set; }
public decimal LatestPrice { get; private set; }
public int Quantity { get; private set; }
public decimal TotalOrder { get {return LatestPrice * Quantity;}}
public OrderItem(string name, decimal price, int quantity)
{
}
public OrderItem(string name, decimal price) : this(name, price, 1)
{
}
}
Above is the class, just for some background.
public void AddProduct(string name, decimal price, int quantity)
{
lstOrderitem.Add(new OrderItem(name, price, quantity));
}
On the code inside the AddProduct method is where I am getting the error stated in the title.
I'm just trying to instantiate the class and add it to a collection to be displayed in a listbox on my form program.
The "AddProduct" will be called on a button click event
Error = NullReferenceException - Object reference not set to an instance of an object.
I was wondering if anybody knew why this was happening since I thought that since I am making a NEW instance of the class while adding it to the list that it would have something to reference too. Thank you if anybody knows what the problem is.
Edit
public List<OrderItem> lstOrderitem{ get; private set; }
public int NumberOfProducts { get; private set; }
public decimal BasketTotal { get; private set; }
public ShoppingBasket()
{
//List<OrderItem> lstOrderitem = new List<OrderItem>();
}
public void AddProduct(string name, decimal price, int quantity)
{
lstOrderitem.Add(new OrderItem(name, price, quantity));
}
A: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your references value is null, you need to initialize lstOrderitem before using it.
A: You should initialize lstOrderitem property in the constructor, like this:
EDIT
public MyClass() {
lstOrderitem = new List<OrderItem>();
}
P.S. Microsoft suggests starting the names of your properties in capital letters, to avoid confusion with member variables, which should be named starting with a lowercase letter.
A: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your reference value is null, you need to initialize lstOrderitem before using it.
public MyClass() {
lstOrderitem = new List<OrderItem>();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8701846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Is there a way to make app engine turn off when no traffic I am currently using App Engine in Google Cloud with Docker to handle Mux Video requests. The problem is I am being charged over $40 when the app is in development and there is virtually no traffic on the app. Is there a way to turn off the App Engine when no requests are being sent so the hours of operation are less or this not possible with app Engine? I am quite new to App Engine.
runtime: custom
env: flex
manual_scaling:
instances: 1
resources:
cpu: 1
memory_gb: 0.5
disk_size_gb: 10
A: No, you can't scale to 0 the Flex instances. It's the main problem of the flex instances.
You have to replace the current service by a APp Engine standard service version that can scale to 0 and stop paying.
If your application doesn't run background processes, and the request handling doesn't take more than 60 minutes, I strongly recommend you to have a look to Cloud Run
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70173388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "save link as" bulk download I have a list of links in an html file and I want to perform a "save link as" for all of them so it downloads all the files into one folder.
Is this possible? I need to do this from within firefox or chrome as I am required to be logged in to the website,
Thanks,
A
A: Whilst it's possible to do this with curl (including the login), I would recommend using a browser extension. Flashgot for Firefox is excellent, you can tell it to download all files of a certain extension, or do things like pattern matching.
http://flashgot.net/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8112283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why do we need to define a function to call another function? In the implementation of ResNet architecture in Pytorch I encountered the code below which is from line 264 til 283:
def _forward_impl(self, x: Tensor) -> Tensor:
# See note [TorchScript super()]
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def forward(self, x: Tensor) -> Tensor:
return self._forward_impl(x)
What is the purpose of _forward_impl? Why didn't the coder bring what is happening inside _forward_impl into forward itself and getting ride of _forward_impl? I see _forward_impl looks like a private method, since it has underscore at the start of its name, however, I cannot yet see what the purpose of _forward_impl is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72111540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read logging configuration from appsettings.json in .net Core 2.2 In .net Core 2.1 it was done like this
var loggingConfig = configuration.GetSection("Logging");
loggerFactory.AddConsole(loggingConfig);
I have moved it to ConfigureServices and now I get
Error CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions'
A: Base on this you may have to change the way you are configuring your application:
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
1 Microsoft ASP.NET Core 2.2 Logging documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54321456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Facebook Likeview is not working I have implemented Like as suggested on Facebook developer site
I just added Likeview and set Object id for post code is as below
likeView = (LikeView)findViewById(R.id.like_view);
likeView.setObjectId("https://www.facebook.com/karan.raj.5070276/posts/396696657159566");
My layout file has LikeView widget
<com.facebook.widget.LikeView
android:id="@+id/like_view"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp" />
On clicking it just opens Dialog for sometime and it disappears without any action
and In log-cat I finds error message like
"Like dialog is only available to developers and tester"
What should I do In my Facebook app. Should I add Roles for developer and tester
Please help any help will be appreciated
A: Login your facebook with same user which you have created facebook app with. This error appeared because you logged in facebook with other user.
Note: By default Facebook app app is in development mode and can only be used by app admins, developers and testers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27821911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Offsets to create n-sided shape around starting point in Javascript I would like to find an function where, given a starting point (x, y) P, a radius r, and an integer n, I can generate offsets from P to create n well-placed points to create a shape (within a circle of radius r) around P.
For example:
For P = {x: 0, y: 0}, r = 25.
Where "offsets" is the return value of the desired function...
Let n = 0:
offsets = [];
Let n = 1:
// Note 25 here is simply P.x + r, where P.x = 0 for simplicity's sake.
// So x: 25 is actually x: P.x + 25
// And y: 0 is actually y: P.y + 0
// I've kept the simplified notation here and below for readability.
offsets = [{x: 25, y: 0}];
Let n = 2: // Line
offsets = [{x: 25, y: 0}, {x: -25, y: 0}];
Let n = 3: // Triangle
offsets = [{x: 25, y: 0}, {x: -25, y: 0}, {x: 0, y: 25}];
Let n = 4: // Square
offsets = [
{x: 25, y: 0},
{x: -25, y: 0},
{x: 0, y: 25},
{x: 0, y: -25}
];
Let n = 5: // Pentagon
offsets = [
{x: 25, y: 0},
{x: -25, y: 0},
{x: 0, y: 25},
{x: -12.5, y: -25},
{x: 12.5, y: -25}
];
.... and so on.
A: Just sample a circle:
allocate offset array
var angle = 2 * Math.PI / n;
for(var i = 0; i < n; ++i)
offsets[i] = {x: r * Math.cos(i * angle), y: r * Math.sin(i * angle)};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33378118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is setuid not running as the owner? I am currently trying to learn what the special bits in file permissions do but am currently stuck trying to understand what the setuid bit does. From all the online resources it says:
Commonly noted as SUID, the special permission for the user access level has a single function: A file with SUID always executes as the user who owns the file, regardless of the user passing the command
However in a simple experiment this just doesn't appear to be true (unless I have misunderstood and am doing something wrong?) i.e.
mkdir /tmp/foo
mkdir /tmp/foo/bar
chmod 0700 /tmp/foo/bar # Restrict directory so only current user can access
echo content > /tmp/foo/bar/baz.txt # Create content in the restricted directory
echo "ls /tmp/foo/bar" > /tmp/foo/myscript.sh # Script to access content of restricted directoy
chmod 4777 /tmp/foo/myscript.sh # Set setuid bit so the script runs as current user
/tmp/foo/myscript.sh # Show it works when run as current user
#> baz.txt
su bob # Switch to a new user
/tmp/foo/myscript.sh # Run script again
#> ls: cannot open directory '/tmp/foo/bar': Permission denied
My expectation was that as the setuid bit was set the script should have been executed as the original user and as such should have had permissions to ls into the restricted directory. But instead I got a permissions denied error indicating that the script was not run as the original user.
Any help into understanding what I'm doing wrong would be greatly appreciated. (example was run on zsh / ubuntu 20.04 / wsl2)
A: The suid bit works only on binary executable programs, not on shell scripts. You can find more info here: https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69958788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Managing users in the TFS work items "Assigned To" field So I know there have been a couple of posts around about this topic, but I don't think they've quite got to the bottom of it!
So my problem is that when I create a new work item in TFS, the users which I can assign it to include NT Authority\Local Service (which is also the TFS service account). I'm not asking why, as I know that this field, by default is populated by the Valid Users group, and upon inspecting the groups, I can see that the group permissions hierarchy looks like this:
-> Valid Users
-> Project Collection Admistrators
-> Project Collection Service Accounts
-> NT Authority\Local Service
And you can't change anything in the project collection service accounts, so surely by default, everyone has this user in the assign to field? So does this mean everyone accepts it, or do they modify their process templates to filter it out (see the blog here)?
Just seems a bit odd to me that by default is isn't filtered out already! Clearly I don't want to be removing this from any permissions either (even if I could) as I'm worried it'll cause problems later.
So is filtering in the process template the only way (which looks like a bit of effort to maintain), or is there a simpler way?
A: Under TFS2008, you do need to do it this way. Under 2010, there might be an "exclude", but I'm not able to check that at the moment.
To keep from having a whole lot of maintenance, instead of listing each user individually, what we did was just pared down the list from "Valid Users" to the "Moderators" and "Contributors". We know that we can control those groups without affecting service permissions:
<FIELD name="Assigned To" refname="System.AssignedTo" type="String" reportable="dimension">
<ALLOWEDVALUES expanditems="true">
<LISTITEM value="[Project]\Contributors"/>
<LISTITEM value="[Project]\Moderators"/>
</ALLOWEDVALUES>
</FIELD>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3422653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Anybody who have used Django and JQuery Autocomplete? Is there anybody out there who have used Django and JQuery Autocomplete? Am stuck on this and i will highly appreciate to see how someone else has done this! especially without using the AutocompleteWidget!
Gath
A: There are some easy to follow examples in this GitHub mirror of django-autocomplete.
A: some time ago I put together a small tutorial on this, you might find that useful... it's here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/738529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Running a docker container which uses GPU from kubernetes fails to find the GPU I want to run a docker container which uses GPU (it runs a cnn to detect objects on a video), and then run that container on Kubernetes.
I can run the container from docker alone without problems, but when I try to run the container from Kubernetes it fails to find the GPU.
I run it using this command:
kubectl exec -it namepod /bin/bash
This is the problem that I get:
kubectl exec -it tym-python-5bb7fcf76b-4c9z6 /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@tym-python-5bb7fcf76b-4c9z6:/opt# cd servicio/
root@tym-python-5bb7fcf76b-4c9z6:/opt/servicio# python3 TM_Servicev2.py
Try to load cfg: /opt/darknet/cfg/yolov4.cfg, weights: /opt/yolov4.weights, clear = 0
CUDA status Error: file: ./src/dark_cuda.c : () : line: 620 : build time: Jul 30 2021 - 14:05:34
CUDA Error: no CUDA-capable device is detected
python3: check_error: Unknown error -1979678822
root@tym-python-5bb7fcf76b-4c9z6:/opt/servicio#
EDIT.
I followed all the steps on the Nvidia docker 2 guide and downloaded the Nvidia plugin for Kubernetes.
however when I deploy Kubernetes it stays as "pending" and never actually starts. I don't get an error anymore, but it never starts.
The pod appears like this:
gpu-pod 0/1 Pending 0 3m19s
EDIT 2.
I ended up reinstalling everything and now my pod appears completed but not running. like this.
default gpu-operator-test 0/1 Completed 0 62m
Answering Wiktor.
when I run this command:
kubectl describe pod gpu-operator-test
I get:
Name: gpu-operator-test
Namespace: default
Priority: 0
Node: pdi-mc/192.168.0.15
Start Time: Mon, 09 Aug 2021 12:09:51 -0500
Labels: <none>
Annotations: cni.projectcalico.org/containerID: 968e49d27fb3d86ed7e70769953279271b675177e188d52d45d7c4926bcdfbb2
cni.projectcalico.org/podIP:
cni.projectcalico.org/podIPs:
Status: Succeeded
IP: 192.168.10.81
IPs:
IP: 192.168.10.81
Containers:
cuda-vector-add:
Container ID: docker://d49545fad730b2ec3ea81a45a85a2fef323edc82e29339cd3603f122abde9cef
Image: nvidia/samples:vectoradd-cuda10.2
Image ID: docker-pullable://nvidia/samples@sha256:4593078cdb8e786d35566faa2b84da1123acea42f0d4099e84e2af0448724af1
Port: <none>
Host Port: <none>
State: Terminated
Reason: Completed
Exit Code: 0
Started: Mon, 09 Aug 2021 12:10:29 -0500
Finished: Mon, 09 Aug 2021 12:10:30 -0500
Ready: False
Restart Count: 0
Limits:
nvidia.com/gpu: 1
Requests:
nvidia.com/gpu: 1
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9ktgq (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
kube-api-access-9ktgq:
Type: Projected (a volume that contains injected data from multiple sources)
TokenExpirationSeconds: 3607
ConfigMapName: kube-root-ca.crt
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events: <none>
I'm using this configuration file to create the pod
apiVersion: v1
kind: Pod
metadata:
name: gpu-operator-test
spec:
restartPolicy: OnFailure
containers:
- name: cuda-vector-add
image: "nvidia/samples:vectoradd-cuda10.2"
resources:
limits:
nvidia.com/gpu: 1
A: Addressing two topics here:
*
*The error you saw at the beginning:
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Means that you tried to use a deprecated version of the kubectl exec command. The proper syntax is:
$ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]
See here for more details.
*According the the official docs the gpu-operator-test pod should run to completion:
You can see that the pod's status is Succeeded and also:
State: Terminated
Reason: Completed
Exit Code: 0
Exit Code: 0 means that the specified container command completed successfully.
More details can be found in the official docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68653976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cant get android sqlite select statement to work I'm trying to select the items that have expired in my database but nothing is ever returned. I've tried the following:
select * from productTable where columnExpiration < date( currentDate)
All dates in the format yyyy-mm-dd
When that didn't work I tried:
Select* from productTable where columnExpiration < currentDate
Any suggestions? This is really starting to drive me crazy. Thanks
A: Try here, which has already been asked, and has a solution:
use Datetime() to format your dates before comparison.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7898612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the number of each elements in the row and store the mean of each row in another array using C#? I am using the below code to read data from a text file row by row. I would like to assign each row into an array. I must be able to find the number or rows/arrays and the number of elements on each one of them.
I would also like to do some manipulations on some or all rows and return their values.
I get the number of rows, but is there a way to to loop something like:
*for ( i=1 to number of rows)
do
mean[i]<-row[i]
done
return mean*
var data = System.IO.File.ReadAllText("Data.txt");
var arrays = new List<float[]>();
var lines = data.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var lineArray = new List<float>();
foreach (var s in line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
{
lineArray.Add(Convert.ToSingle(s));
}
arrays.Add(lineArray.ToArray());
}
var numberOfRows = lines.Count();
var numberOfValues = arrays.Sum(s => s.Length);
A: var arrays = new List<float[]>();
//....your filling the arrays
var averages = arrays.Select(floats => floats.Average()).ToArray(); //float[]
var counts = arrays.Select(floats => floats.Count()).ToArray(); //int[]
A: Not sure I understood the question. Do you mean something like
foreach (string line in File.ReadAllLines("fileName.txt")
{
...
}
A: Is it ok for you to use Linq? You might need to add using System.Linq; at the top.
float floatTester = 0;
List<float[]> result = File.ReadLines(@"Data.txt")
.Where(l => !string.IsNullOrWhiteSpace(l))
.Select(l => new {Line = l, Fields = l.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) })
.Select(x => x.Fields
.Where(f => Single.TryParse(f, out floatTester))
.Select(f => floatTester).ToArray())
.ToList();
// now get your totals
int numberOfLinesWithData = result.Count;
int numberOfAllFloats = result.Sum(fa => fa.Length);
Explanation:
*
*File.ReadLines reads the lines of a file (not all at once but straming)
*Where returns only elements for which the given predicate is true(f.e. the line must contain more than empty text)
*new { creates an anonymous type with the given properties(f.e. the fields separated by comma)
*Then i try to parse each field to float
*All that can be parsed will be added to an float[] with ToArray()
*All together will be added to a List<float[]> with ToList()
A: Found an efficient way to do this. Thanks for your input everybody!
private void ReadFile()
{
var lines = File.ReadLines("Data.csv");
var numbers = new List<List<double>>();
var separators = new[] { ',', ' ' };
/*System.Threading.Tasks.*/
Parallel.ForEach(lines, line =>
{
var list = new List<double>();
foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))
{
double i;
if (double.TryParse(s, out i))
{
list.Add(i);
}
}
lock (numbers)
{
numbers.Add(list);
}
});
var rowTotal = new double[numbers.Count];
var rowMean = new double[numbers.Count];
var totalInRow = new int[numbers.Count()];
for (var row = 0; row < numbers.Count; row++)
{
var values = numbers[row].ToArray();
rowTotal[row] = values.Sum();
rowMean[row] = rowTotal[row] / values.Length;
totalInRow[row] += values.Length;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11541076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Audio not working in html5 I was adding audio to an HTML5 website. The audio works fine with FireFox and IE but does not show up and play in FireFox. Any ideas why and solution? Thanks in advance.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<audio controls="controls" autoplay="autoplay">
<source src="cd.mp3" type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
</body>
</html>
A: Firefox doesn't support MP3. It won't show the fallback message because it supports the audio tag.
https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements#MPEG_H.264_(AAC_or_MP3)
A: You can't play MP3 files with such a code in Firefox.
See https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10667932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: TextInfo ToTitleCase missing in Xamarin Forms I am trying to convert a string to title case in my cross platform Xamarin app using the following code.
string rawString = "this is a test string";
System.Globalization.TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
string formattedString = textInfo.ToTitleCase(rawString);
//Expected output is "This Is A Test String"
I cannot run this code as the compiler insists that there is no definition for ToTitleCase in TextInfo. However the documentation says otherwise.
I am using Visual Studio 2017 with the latest NuGet packages for everything (including all .Net packages and Xamarin.Forms)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50333596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Group By and Sum Quantity by Direction Column Good Day guys is there a way for me to group by an item and sum its quantity using the direction column?
I want to add new column positive_quantity (direction are 1, 4, 5)
and negative_quantity (direction are 2, 3, 6)
here's my code:
SELECT
il.warehouse_id,
w.code as warehouse_code,
w.name as warehouse_name,
il.item_id,
i.code as item_code,
i.name as item_name,
il.lot,
il.date_expiry,
il.direction,
il.location_id,
//SUM(il.qty), as posive_quantity (base on direction 1, 4, 5)
//SUM(il.qty), as negative_quantity (base on direction 2, 3, 6)
FROM warehouses w
INNER JOIN inventory_logs il
ON w.id = il.warehouse_id
INNER JOIN items as i
ON il.item_id = i.id
WHERE il.location_id IN (1,3) AND il.date_posted BETWEEN '2019-01-01' AND '2019-01-31'
GROUP BY
il.warehouse_id,
il.item_id,
il.lot,
il.date_expiry,
il.location_id,
direction
here is my desired output:
Thank you in advance. I have also tried using temporary table but it gives me error. like using the same temporary error.
A: You can use conditional sum:
SELECT
il.warehouse_id,
w.code as warehouse_code,
w.name as warehouse_name,
il.item_id,
i.code as item_code,
i.name as item_name,
il.lot,
il.date_expiry,
il.location_id,
sum( if( il.direction in (1,4,5), il.qty, 0 ) ) as positive_quantity,
sum( if( il.direction in (2, 3, 6), il.qty, 0 ) ) as negative_quantity
FROM warehouses w
INNER JOIN inventory_logs il
ON w.id = il.warehouse_id
INNER JOIN items as i
ON il.item_id = i.id
WHERE il.location_id IN (1,3) AND il.date_posted BETWEEN '2019-01-01' AND '2019-01-31'
GROUP BY
il.warehouse_id,
il.item_id,
il.lot,
il.date_expiry,
il.location_id,
Btw, your images dot match with the query. It is always best to post the question as text instead of an image, preferably as an SQLFiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58077607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I use create a program that uses GDI+ 1.0 on XP and 1.1 on Vista/Win7 I know that if I use the features of GDI+ 1.1, the .EXE file won't run on Windows XP.
I want to make a program that runs on Windows XP and Windows 7 both, and use the GDI+ 1.1 feature on Win7.
Is there anyway to do this?
A: A simple way to do it is to put your GDI+ 1.1 code in #ifdefs and compile it to two different DLLs -- one with the code and one without. Then at runtime load the DLL that will work. Maybe you could even attempt to load the 1.1 DLL and if that fails fall back to the 1.0 DLL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7398145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use "-replace" in Set-ADUser? I want to use PowerShell via my C# to modify Active Directory attributes. Here is my PowerShell command which I can use to replace an Active Directory attribute:
Set-ADUser -Identity "kchnam" -Replace @{extensionAttribute2="Neuer Wert"}
How can I add the @{extensionAttribute2="Neuer Wert"} to my C# command?
My solution is not working:
Command setUser = new Command("Set-ADUser");
setUser.Parameters.Add("Identity", aduser);
string testadd = "@{extensionAttribute2=" + quote + "Neuer Wert" + quote + "}";
setUser.Parameters.Add("Replace", testadd);
A: In PowerShell that:
@{extensionAttribute2="Neuer Wert"}
means a Hashtable literal, not just string. So, in C# you also have to create a Hashtable object:
new Hashtable{{"extensionAttribute2","Neuer Wert"}}
Although, that is not fully equivalent to PowerShell, since PowerShell create Hashtable with case insensitive key comparer. But, very likely, that you can use any collection implementing IDictionary, not just a Hashtable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31921187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Visual Studio Code, container: terminal hangs very long before prompt appears I'm using Visual Studio Code to develop within a Docker container (notably, mcr.microsoft.com/vscode/devcontainers/javascript-node:0-12).
This is the content of my settings.json file:
{
"terminal.integrated.defaultProfile.linux": "zsh",
"terminal.integrated.profiles.linux": {
"bash": {
"path": "/usr/bin/flatpak-spawn",
"args": [
"--host",
"--env=TERM=xterm-256color",
"bash"
]
}
}
}
When I issue any command in the terminal, it executes correctly, but it takes very long for the prompt to appear again.
What is causing this behaviour? How can the problem be solved?
A: It turned out that the delay was due to a combination of:
*
*poor container's file system behaviour because bind-mount'ed to the local machine's one (Linux container on Windows machine)
*project consisting of a large number of (small, actually) source files (~10,000)
*git information displayed on the prompt
To solve the issue, I ended up disabling git's processing every time (as described at https://giters.com/ohmyzsh/ohmyzsh/issues/9848 ), by adding a postCreateCommand in devcontainer.json file.
This is the content of my devcontainer.json:
"postCreateCommand": "git config --global oh-my-zsh.hide-info 1 && git config --global oh-my-zsh.hide-status 1 && git config --global oh-my-zsh.hide-dirty 1"
A: With recent vscode devcontainers, I found that I needed to do something like this instead, as bash appears to be the default shell, instead of zsh.
"postCreateCommand": "git config --global codespaces-theme.hide-info 1 && git config --global codespaces-theme.hide-status 1 && git config --global codespaces-theme.hide-dirty 1"
See: https://github.com/microsoft/vscode-dev-containers/issues/1196
There might be additional changes coming as well, based on https://github.com/devcontainers/features/pull/326
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70861778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: use vmalloc memory to do DMA? I'm writing a driver which need large memory. Let's say it will be 1GB at least.
The kernel version >= 3.10.
Driver needs run in X86_64 and Arm platform.
The hardware may have IOMMU.
*
*This large memory will mmap to userspace.
*Device use those memory to do DMA. Each DMA operation just write max 2KB size of data to those memory.
My Questions.
*
*vmalloc can give me large non-physical-continus pages. Can I use vmalloc get large memory to do DMA? I'm thinking use vmalloc_to_page to get page pointer then use page_to_phys to get physical address.
*I found a info about "vmalloc performance is lower than kmalloc." I'm not sure what it means.
if I do vaddr = vmalloc(2MB) and kaddr = kmalloc(2MB), the function call of vmalloc will be slower than kmalloc because of memory remap. But is memory access in range [vaddr, vaddr+2MB) will slower than [kaddr, kaddr+2MB) ? The large memory will be created during driver init, so does vmalloc memory cause performance issue?
*DMA needs dma_map_single to get dma_addr_t. I'm thinking use dma_map_single to get all the page's dma address at driver init. I will just use those dma address when driver need to do DMA. Can I do this to get some performance improvment?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61092347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Batch update in php I have a mysql table with multiple fields:
SNo id status
Now the status has changed and i need to update it when the value of Sno is 1 from my php script. I do not want to do it individually as this may be time consuming. Is there any way to update the values of status when I have the value of Sno which it corresponds to other than deleting these columns and doing an insert again.
The value of new status is not a constant. Lets assume that there are 4 entries with sno 1 and the status field is originally all false. Now lets say I want to update it and have a string true,true,false,false. I want the staus to be updated to true,true,flase,false exactly in the order that they appear in the table.
A: Not completely sure what you mean, but I think you are looking for:
UPDATE `table` SET `status` = 'new status' WHERE `SNo` = '1'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12831197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Confluent KSQL "Register a stream or table for this topic" doesn't populate topic fields I have 4 topics where I was able to successfully stream data to, and their schemas look good.
But after clicking a topic > "Query in KSQL", I noticed only 1 of them populates the "Field(s) you'd like to include in your STREAM". The other 3 show up blank like so:
I noticed the topic that was able to populate the KSQL fields has a surrogate int primary key called id whereas the ones that don't work have a natural string primary key called boxId e.g. "ABC123", if that has anything to do with it?
What am I missing to get those fields to populate?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59534357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python spark Dataframe to Elasticsearch I can't figure out how to write a dataframe to elasticsearch using python from spark. I followed the steps from here.
Here is my code:
# Read file
df = sqlContext.read \
.format('com.databricks.spark.csv') \
.options(header='true') \
.load('/vagrant/data/input/input.csv', schema = customSchema)
df.registerTempTable("data")
# KPIs
kpi1 = sqlContext.sql("SELECT * FROM data")
es_conf = {"es.nodes" : "10.10.10.10","es.port" : "9200","es.resource" : "kpi"}
kpi1.rdd.saveAsNewAPIHadoopFile(
path='-',
outputFormatClass="org.elasticsearch.hadoop.mr.EsOutputFormat",
keyClass="org.apache.hadoop.io.NullWritable",
valueClass="org.elasticsearch.hadoop.mr.LinkedMapWritable",
conf=es_conf)
Above code gives
Caused by: net.razorvine.pickle.PickleException: expected zero
arguments for construction of ClassDict (for
pyspark.sql.types._create_row)
I also started the script from:
spark-submit --master spark://aggregator:7077 --jars ../jars/elasticsearch-hadoop-2.4.0/dist/elasticsearch-hadoop-2.4.0.jar /vagrant/scripts/aggregation.py to ensure that elasticsearch-hadoop is loaded
A: For starters saveAsNewAPIHadoopFile expects a RDD of (key, value) pairs and in your case this may happen only accidentally. The same thing applies to the value format you declare.
I am not familiar with Elastic but just based on the arguments you should probably try something similar to this:
kpi1.rdd.map(lambda row: (None, row.asDict()).saveAsNewAPIHadoopFile(...)
Since Elastic-Hadoop provide SQL Data Source you should be also able to skip that and save data directly:
df.write.format("org.elasticsearch.spark.sql").save(...)
A: As zero323 said, the easiest way to load a Dataframe from PySpark to Elasticsearch is with the method
Dataframe.write.format("org.elasticsearch.spark.sql").save("index/type")
A: You can use something like this:
df.write.mode('overwrite').format("org.elasticsearch.spark.sql").option("es.resource", '%s/%s' % (conf['index'], conf['doc_type'])).option("es.nodes", conf['host']).option("es.port", conf['port']).save()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39559121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: sycn a vertical recyclerview with and horizontal recyclerview I am creating a food menu layout, the menu has categories with items.
at the top is a list of category names like drinks, sushi, etc, which is a recyclerview that scrolls horizontally, at the bottom are the category items for example under drinks there is cocacola Fanta, etc which is a recyclerview that scrolls vertically. I am trying to synch the two recyclerviews together with a behavior in which when you scroll the vertical, it scrolls the horizontal and vice versa.
I created this class to implement this feature.
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
class TwoRecyclerViews(
private val recyclerViewHorizontal: RecyclerView,
private val recyclerViewVertical: RecyclerView,
private var indices: List<Int>,
private var isSmoothScroll: Boolean = false,
) {
private var attached = false
private var horizontalRecyclerState = RecyclerView.SCROLL_STATE_IDLE
private var verticalRecyclerState = RecyclerView.SCROLL_STATE_IDLE
private val smoothScrollerVertical: RecyclerView.SmoothScroller =
object : LinearSmoothScroller(recyclerViewVertical.context) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}
fun attach() {
recyclerViewHorizontal.adapter
?: throw RuntimeException("Cannot attach with no Adapter provided to RecyclerView")
recyclerViewVertical.adapter
?: throw RuntimeException("Cannot attach with no Adapter provided to RecyclerView")
updateFirstPosition()
notifyIndicesChanged()
attached = true
}
private fun detach() {
recyclerViewVertical.clearOnScrollListeners()
recyclerViewHorizontal.clearOnScrollListeners()
}
fun reAttach() {
detach()
attach()
}
private fun updateFirstPosition() {
Handler(Looper.getMainLooper()).postDelayed({
val view = recyclerViewHorizontal.findViewHolderForLayoutPosition(0)?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))
}, 100)
}
fun isAttached() = attached
private fun notifyIndicesChanged() {
recyclerViewHorizontal.addOnScrollListener(onHorizontalScrollListener)
recyclerViewVertical.addOnScrollListener(onVerticalScrollListener)
}
private val onHorizontalScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
horizontalRecyclerState = newState
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val linearLayoutManager: LinearLayoutManager =
recyclerView.layoutManager as LinearLayoutManager?
?: throw RuntimeException("No LinearLayoutManager attached to the RecyclerView.")
var itemPosition =
linearLayoutManager.findFirstCompletelyVisibleItemPosition()
if (itemPosition == -1) {
itemPosition =
linearLayoutManager.findFirstVisibleItemPosition()
}
if (horizontalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||
horizontalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING
) {
for (position in indices.indices) {
val view = recyclerView.findViewHolderForLayoutPosition(indices[position])?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
if (itemPosition == indices[position]) {
if (isSmoothScroll) {
smoothScrollerVertical.targetPosition = indices[position]
recyclerViewVertical.layoutManager?.startSmoothScroll(smoothScrollerVertical)
} else {
(recyclerViewVertical.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(
indices[position], 16.dpToPx()
)
}
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerView.context.getColor(R.color.primary_1))
} else {
imageView?.visibility = View.GONE
textView?.setTypeface(null, Typeface.NORMAL)
textView?.setTextColor(recyclerView.context.getColor(R.color.secondary_5))
}
}
}
}
}
private val onVerticalScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
verticalRecyclerState = newState
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val linearLayoutManager: LinearLayoutManager =
recyclerView.layoutManager as LinearLayoutManager?
?: throw RuntimeException("No LinearLayoutManager attached to the RecyclerView.")
var itemPosition =
linearLayoutManager.findFirstCompletelyVisibleItemPosition()
if (itemPosition == -1) {
itemPosition =
linearLayoutManager.findFirstVisibleItemPosition()
}
if (verticalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||
verticalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING
) {
for (position in indices.indices) {
val view = recyclerViewHorizontal.findViewHolderForAdapterPosition(indices[position])?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
if (itemPosition == indices[position]) {
(recyclerViewHorizontal.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(
indices[position], 16.dpToPx()
)
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))
} else {
imageView?.visibility = View.GONE
textView?.setTypeface(null, Typeface.NORMAL)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.secondary_5))
}
}
}
}
}
}
the class works fine for the vertical scroll, but there is an instability with the horizontal scroll. if you also have a better solution than the class i created kindly share.
A: The best way to achieve your UI/UX requirement is to use TabLayout with a vertical recycler view.
Both list items in the recycler view and tabs in the tab layout can be set up as a dynamic number of items/tabs
When you scroll up and down and reach the respective category, update the tab layout using the following code. You can identify each category from the
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); // Once for the Activity of Fragment
TabLayout.Tab tab = tabLayout.getTabAt(someIndex); // Some index should be obtain from the dataset
tab.select();
In the same way, when clicking on a tab or scrolling the tab layout, Update the RecyclerVew accordingly./
recyclerView.smoothScrollToPosition(itemCount)
Hope this will help, Cheers!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74567007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found I'm trying to install bern2 locally. bern2 installed successfully. when I started running, I got this error.
ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)
from normalizers.neural_normalizer import NeuralNormalizer
File "/home/ubuntu/BERN2/BERN2/normalizers/neural_normalizer.py", line 17, in <module>
import faiss
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/__init__.py", line 18, in <module>
from .loader import *
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/loader.py", line 65, in <module>
from .swigfaiss import *
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/swigfaiss.py", line 10, in <module>
from . import _swigfaiss
ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)
Traceback (most recent call last):
File "/home/ubuntu/BERN2/BERN2/server.py", line 1, in <module>
from app import create_app
File "/home/ubuntu/BERN2/BERN2/app/__init__.py", line 12, in <module>
import bern2
File "/home/ubuntu/BERN2/BERN2/bern2/__init__.py", line 1, in <module>
from bern2.bern2 import BERN2
File "/home/ubuntu/BERN2/BERN2/bern2/bern2.py", line 22, in <module>
from normalizer import Normalizer
File "/home/ubuntu/BERN2/BERN2/bern2/normalizer.py", line 11, in <module>
from normalizers.neural_normalizer import NeuralNormalizer
File "/home/ubuntu/BERN2/BERN2/normalizers/neural_normalizer.py", line 17, in <module>
import faiss
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/__init__.py", line 18, in <module>
from .loader import *
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/loader.py", line 65, in <module>
from .swigfaiss import *
File "/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/swigfaiss.py", line 10, in <module>
from . import _swigfaiss
ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)
A: The reason could be that the system path is not configured correctly. Try this,
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/
Source:
https://www.tensorflow.org/install/pip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74556574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: css: make inner container height 100% with top and bottom margin I have strange case:
I try to make an inner container to fill parent (height with 100% height), but as result I get overflowed content in bottom:
But it must be so (100% except margin top and bottom):
code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="main-wrapper">
<aside class="full-nav" action-bar>
</aside>
<section class="wrapper">
<header>
</header>
<div class="content">
<div class="innner-wrapper">
<div class="main-partial">
<div class="content-wrapper">Content</div>
</div>
</div>
</div>
</section>
</div>
</body>
</html>
and plunker (CSSit there):
http://plnkr.co/edit/ku7ZXK6uezfZ86cMFhds?p=preview
(when I set absolute position I get strange width...)
A: You can calculate the height of the .content-wrapper and adjust it.
.content-wrapper {
height: calc(100% - 70px);
}
Output:
/* Styles go here */
html,
body {
height: 100%;
min-height: 100%;
}
body {
min-width: 1024px;
font-family: 'Open Sans', sans-serif;
margin: 0;
padding: 0;
border: 0;
}
.pull-right {
float: left;
}
.pull-left {
float: left;
}
.main-wrapper {
width: 100%;
height: 100%;
}
aside {
width: 48px;
height: 100%;
float: left;
background: #dedede;
position: absolute;
}
aside.full-nav {
width: 168px;
}
section.wrapper {
width: 100%;
height: 100%;
float: left;
padding-left: 168px;
background: #eeeeee;
}
section.wrapper.full-size {
padding-left: 48px;
}
aside ul.full-width {
width: 100%;
list-style-type: none;
}
aside nav ul li {
height: 34px;
}
aside nav ul li:hover {
opacity: 0.9;
}
aside.full-nav nav ul li.company-name {
width: 100%;
height: 80px;
background: #717cba;
position: relative;
}
aside.full-nav nav ul li.company-name span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
aside nav ul li a {
height: 34px;
line-height: 1;
max-height: 34px;
font-size: 14px;
font-weight: 400;
color: #ffffff;
margin: 5px 0 0 12px;
text-decoration: none;
display: block;
}
aside.full-nav nav ul li a.first {
margin: 20px 0 0 12px;
text-decoration: none;
}
aside nav ul li a:hover {
color: #ffffff;
}
aside nav ul li.company-name .nav-company-overflow {
display: none;
}
aside nav ul li.company-name .nav-company-logo {
display: none;
}
aside.full-nav nav ul li.company-name a {
height: 16px;
color: #ffffff;
margin: 10px 0 0 12px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.35);
position: absolute;
z-index: 20;
}
aside.full-nav nav ul li.company-name .nav-company-overflow {
width: 168px;
height: 80px;
position: absolute;
top: 0;
background: rgba(78, 91, 169, 0.8);
z-index: 15;
display: block;
}
aside.full-nav nav ul li.company-name .nav-company-logo {
width: 168px;
height: 80px;
position: absolute;
top: 0;
z-index: 10;
display: block;
}
aside nav ul li a em {
line-height: 100%;
display: inline-block;
vertical-align: middle;
margin: 0 18px 0 0;
}
aside nav ul li a span {
width: 110px;
display: inline-block;
line-height: 100%;
vertical-align: middle;
max-width: 110px;
}
aside nav ul li a.profile em {
width: 18px;
height: 18px;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -676px;
margin: 6px 8px 0 0;
}
aside.full-nav nav ul li a.profile em {
margin: 0 8px 0 0;
}
aside nav ul li a.contacts em {
width: 20px;
height: 20px;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -224px;
}
aside nav ul li a.events em {
width: 20px;
height: 22px;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -268px;
}
aside nav ul li a.policy em {
width: 20px;
height: 23px;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -310px;
}
aside nav ul li a.admins em {
width: 18px;
height: 18px;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -676px;
}
aside.full-nav nav ul li a span {
display: inline-block;
}
aside nav ul li a span {
display: none;
}
aside .hide-sidebar {
width: 100%;
height: 34px;
background: #455095;
position: absolute;
bottom: 0;
}
#hide-sidebar-btn {
width: 30px;
height: 34px;
line-height: 40px;
background: #394485;
float: right;
text-align: center;
}
#hide-sidebar-btn:hover {
cursor: pointer;
}
aside .collapse-btn-icon {
width: 8px;
height: 15px;
display: inline-block;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -353px;
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
}
aside.full-nav .collapse-btn-icon {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
.innner-wrapper {
height: 100%;
margin: 0 12px 0 12px;
}
.main-partial {
height: 100%;
}
header {
height: 40px;
background: #ffffff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
header .buttons-header-area {
float: right;
}
header .company-header-avatar {
width: 28px;
height: 28px;
-webkit-border-radius: 28px;
-webkit-background-clip: padding-box;
-moz-border-radius: 28px;
-moz-background-clip: padding;
border-radius: 28px;
background-clip: padding-box;
margin: 7px 0 0 5px;
float: left;
}
header .info {
height: 40px;
line-height: 40px;
margin: 0 5px 0 0;
}
header .info em {
width: 28px;
height: 28px;
display: inline-block;
vertical-align: middle;
background: url(../images/png/profile_spritesheet.png);
background-position: -10px -53px;
}
header .dropdown-toggle {
width: 170px;
height: 40px;
border: none;
padding: 0;
background: transparent;
font-size: 12px;
color: #444444;
}
header .btn-group {
height: 40px;
vertical-align: top;
}
header .btn-group.open {
background: #eeeeee;
}
header .open > .dropdown-menu {
width: 170px;
font-size: 12px;
border-color: #d9d9d9;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.11);
margin: 2px 0 0 0;
}
header .dropdown-toggle:hover {
background: #eeeeee;
}
header .profile-name {
width: 100px;
height: 40px;
line-height: 40px;
display: inline-block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
header .caret {
height: 40px;
border-top: 6px solid #bfbfbf;
border-right: 6px solid transparent;
border-left: 6px solid transparent;
}
.content {
height: 100%;
margin: 12px 0;
overflow: hidden;
}
.content-wrapper {
background: #ffffff none repeat scroll 0 0;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
height: calc(100% - 70px);
width: 100%;
}
.content-row.company {
height: 300px;
}
.content-row-wrapper {
margin: 0 18px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="main-wrapper">
<aside class="full-nav" action-bar>
</aside>
<section class="wrapper">
<header>
</header>
<div class="content">
<div class="innner-wrapper">
<div class="main-partial">
<div class="content-wrapper">Content</div>
</div>
</div>
</div>
</section>
</div>
</body>
</html>
A: I think the problem is that you are assigning 100% height to the container and this one is getting the relative window height. The problem is the header at the top of the page does not let this to work. Maybe you have to calculate with javascript or something to apply the correct height to that container.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31233811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hadoop - Creating a single instance of a class for each map() functions inside the Mapper for a particular node I have a Class something like this in java for hadoop MapReduce
public Class MyClass {
public static MyClassMapper extends Mapper {
static SomeClass someClassObj = new SomeClass();
void map(Object Key, Text value, Context context) {
String someText = someClassObj.getSomeThing();
}
}
}
I need only a single instance of someClassObj to be available to the map() function per node.
How can achieve that?
Please feel free to ask if you need further details on this topic.
Thank you!
A: The mapreduce.tasktracker.map.tasks.maximum (defaulted to 2) controls the maximum number of map tasks that are run simultaneously by a TaskTracker. Set this value to 1.
Each map task is launched is a seperate JVM. Also set the mapreduce.job.jvm.numtasks to -1 to reuse the JVM.
The above settings will enable all the map tasks to run in single JVM sequentially. Now, SomeClass has to be made a singleton class.
This is not a best practice as the node is not efficiently utilized because of the lower number of map tasks that can run in parallel. Also, with JVM reuse there is no isolation between the tasks, so if there is any memory leak it will be carried on till the jvm crashes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7872830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: using Socket.io with React and Redux to handle a hundred of updates per second I have a list of items which are objects of data from the server (about 1000) that I need to sort, filter, put into Redux and connect to a React table component. I'm using socket.io to listen for updates which sends these individual data objects that then need to be calculated into the table. they can be an update, new one or, removing existing one.
So my question is what's the best way to manage so many incoming socket data events? should i just throttle them before i update them into my redux state? i dont want to constantly update my redux state or my table component will re-render too much.
my other option is i can request a current up to date list of all the "active" data and just ignore the update events. so perhaps every few seconds just update the entire table with all the latest data instead of trying to manage hundreds of updates a second.
A: I would stick to using REST api calls, but faking the update on the start of a redux's action, doing nothing except maybe adding a proper id to your object on success, and reverting back the state on failure only.
Your reducer would kinda look like this in case of a create item action :
export default (state = {}, action) => {
switch (action.type) {
case ActionsTypes.CREATE_START:
// make the temporary changes
case ActionsTypes.CREATE_SUCCESS:
// update the previous temporary id with a proper id
case ActionsTypes.CREATE_FAILURE:
// delete the temporary changes
default:
return state;
}
};
And your actions like this :
const ActionLoading = item => ({
type: ActionsTypes.CREATE_START,
item,
});
const ActionSuccess = item => ({
type: ActionsTypes.CREATE_SUCCESS,
item ,
createdItem,
});
const ActionFailure = item => ({
type: ActionsTypes.CREATE_FAILURE,
item,
});
export default todo => (dispatch) => {
dispatch(ActionLoading(item)); // add the item to your state
const updatedTodo = await TodoClient.create(todo)
if (updatedTodo) {
dispatch(ActionSuccess(item, createdItem)) // update the temp item with a real id
} else {
dispatch(ActionFailure(item)) // remove the temporary item
}
};
It is mandatory that you give temporary ids to the data you are managing for performace's sake and to let react key properly the items rendered in maps. I personally use lodash's uniqueId.
You'll have also to implement this behavior for updates and removals but it's basically the same:
*
*store the changes, update your object without waiting for the api and
revert the changes on failure.
*remove your object without waiting for the api and pop it back on failure.
This will give a real time feel as everything will be updated instantly and only reverted on unmanaged errors. If you trust your backend enough, this is the way to go.
EDIT : Just saw your update, you can stick to this way of mutating the data (or to the normal way of updating the state on success) but to avoid too much complexity and rendering time, make sure you store your data using keyBy. Once your items are stored as an array of object keyed by their id, you will be able to add, remove and modify them with a O(1) complexity. Also, react will understand that it doesn't need to re-render the whole list but only the single updated item.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50999907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VueJS - standard practice for ordering functions in export? New to Vue and wondering if there is there a standard practice for ordering the exports? The name seems to always be at the top and the lifecycle hooks seem to be in the order of the lifescycle but I'm not sure about the rest (data, computed, etc.).
Thoughts?
e.g.
export default {
name: "component-name",
props: {},
components: {},
computed: {},
data() {},
watch: {},
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {},
beforeUpdate() {},
updated() {},
beforeDestroy() {},
destroyed() {},
methods: {},
};
A: Based on the rules of the eslint-plugin-vue v6.2.2 (for Vue 2.x), You can read about it here: https://github.com/vuejs/eslint-plugin-vue/blob/v6.2.2/docs/rules/README.md, this is the order:
{
"vue/order-in-components": ["error", {
"order": [
"el",
"name",
"parent",
"functional",
["delimiters", "comments"],
["components", "directives", "filters"],
"extends",
"mixins",
"inheritAttrs",
"model",
["props", "propsData"],
"fetch",
"asyncData",
"data",
"computed",
"watch",
"LIFECYCLE_HOOKS",
"methods",
"head",
["template", "render"],
"renderError"
]
}]
}
Here you can read the Vue style guide and the rules priority information https://v2.vuejs.org/v2/style-guide/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62253825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python error importing dateutil I try to execute marathon-lb.py and it throws the next error:
Traceback (most recent call last):
File "./marathon_lb.py", line 46, in <module>
import dateutil.parser
ImportError: No module named 'dateutil'
I just install python with apt and with pip.
I have run:
sudo apt-get install python-pip
pip install python-dateutil
I compile the script with: python -m py_compile script.py
python application:
from operator import attrgetter
from shutil import move
from tempfile import mkstemp
from wsgiref.simple_server import make_server
from six.moves.urllib import parse
from itertools import cycle
from common import *
from config import *
from lrucache import *
from utils import *
import argparse
import json
import logging
import os
import os.path
import stat
import re
import requests
import shlex
import subprocess
import sys
import time
import dateutil.parser
A: Install python-dateutil
pip install python-dateutil
A: Step 1. First thing is upgrade pip for corresponding python version (3 or 2) you have.
pip3 install --upgrade pip
or
pip2 install --upgrade pip
Step2.
Some times directly running command wont work since
There are probably multiple versions of python-dateutil installed.
*
*Try to run pip uninstall python-dateutil
will give below message if python-dateutil is already un installed.
Cannot uninstall requirement python-dateutil, not installed
*Then, you can run pip install python-dateutil again.
NOTE : Directly running step2 wont work for users whose python and pip versions are not compatible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37434917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |