id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23534400
|
$query = "this is not the problem";
$ora_stmt = oci_parse($conn, $query);
$result = oci_execute($ora_stmt);
$stmt1 = $mysqli1->prepare("INSERT INTO na_dslam_card (n_alias, shelf_pt_num, card_pt_num, card_pt_description)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE n_alias=?, shelf_pt_num=?, card_pt_num=?, card_pt_description=?");
while($row = oci_fetch_array($ora_stmt, OCI_ASSOC+OCI_RETURN_NULLS)) {
print $row['DSLAM'] . "," . $row['MODEL'] . "," . $row['VENDOR'] . "," . $row['BROADBAND_CIRCUIT_ID'] . "," . $row['SVC_N'] . "," . $row['PORT_ADDR_STATUS']. "," . $row['BROADBAND_CIRCUIT_ID'] . "," . $row['RACK'] . "," . $row['SHELF'] . "," . $row['SLOT'] . "," . $row['PORT'] . "," . $row['SHELF_PT_NUMBER'] . "," . $row['CARD_PT_NUMBER'] . "," . $row['CARD_PT_DESCRIPTION'] . "\n";
$stmt1->bind_param("ssss", $row['DSLAM'],$row['SHELF_PT_NUMBER'],$row['CARD_PT_NUMBER'],$row['CARD_PT_DESCRIPTION']);
if(!$stmt1->execute())
{
$tempErr = "Error setting card info: " . $stmt1->error;
printf($tempErr . "\n"); //show mysql execute error if exists
$err->logThis($tempErr);
}
} //while
I get this error message:
Error setting card info: No data supplied for parameters in prepared
statement
I used bind_parameters, so it shouldn't say I didn't supply the parameter data. I know rack can be null sometimes, but wouldn't it just set it to null in that case? I know the oracle query works because the print statement shows this:
CNVLDAT00,TA12,Ad,196,641,In Service,196,,2,,7,117,115,11L5
So why are the parameters not supplied correctly? It looks ok to me.
I looked at insert values and I think I'm doing that ok.
My table looks like this:
na_dslam_card:
index
n_alias
shelf_pt_num
card_pt_num
card_pt_description
Thanks for any help...
A: There are eight bind placeholders in the SQL text. We would need to supply eight values.
The bind_param is only supplying four values.
But rather than supply eight values, we can modify the SQL text to replace the placeholders in the UPDATE clause with the VALUES() function, to reference the value that would have been inserted into the column.
INSERT INTO na_dslam_card
( n_alias
, shelf_pt_num
, card_pt_num
, card_pt_description
)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY
UPDATE n_alias = VALUES(alias)
, shelf_pt_num = VALUES(shelf_pt_num)
, card_pt_num = VALUES(card_pt_num)
, card_pt_description = VALUES(card_pt_description)
Now there are only four placeholders that need values.
Excerpt from MySQL Reference Manual:
In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement. In other words, VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred.
References:
https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
| |
doc_23534401
|
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(R.id.numbers);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
@Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
startActivity(numbersIntent);
}
});
In the line:
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
Why is MainActivity.this used and why can't we use this.
A: Because here new View.OnClickListener() is anonymous inner class.
| |
doc_23534402
|
From what I understand, there are two issues with our app.
*
*First we need to declare sensitive permissions in App Content Center
*However since the app is suspended App Content page is not clickable.
*Since I didn't declare sensitive permissions in App Content, I can't submit new version of the app that will lift the suspension.
From what I see, we are in a deadlock. Did anyone else face this issue before? Any suggestions would be appreciated.
| |
doc_23534403
|
procedure TForm_Master.tv_1Down(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
tv_1.FontColor := TAlphaColors.Dodgerblue;
end;
What could possibly be going wrong?
A: If we set HitTest to True, this control captures all mouse OnClick and OnDblClick events.
If we set HitTest to False, these two mouse-click events will pass through this control, so that a control laid out behind this one receives the mouse events instead of this control.
For most controls, HitTest is True by default. However, this is not true for TLabel and TPathLabel, where HitTest is False by default; these two controls do not capture the OnClick and OnDblClick events unless you set HitTest to True.
http://docwiki.embarcadero.com/Libraries/XE8/en/FMX.Controls.TControl.HitTest
A: Unfortunately Machado's solution does not appear to work when using styles and programmatically created labels.
In such cases, it is easier to create a button style that looks like a label (e.g. in the StyleBook set its background opacity to 0), and then use the styled button instead of a label.
In your case the TNotifyEvent event you fire by setting the OnClick property of the styled button would then change the style of any objects as needed. Using styles can help maintain a consistent look. E.g. place the TStyleBook in an empty form, and inherit the app's other froms from that base form.
| |
doc_23534404
|
I populate datasource
categories.push({ parentNode : d.parentNode,
node: d.node,
identity: d.identity,
key: d.key,
value : d.value,
categories : []
});
I set datasource and group
dataSource = new kendo.data.DataSource({data: categories);
dataSource.group({ field: "value" });
I then want to filter by node but the only option to filter appears to be the grouped value.
A: I punted and changed the data source to hierarchical which allowed me to do what I needed.
A: Just add square bracket in group line
dataSource = new kendo.data.DataSource({data: categories);
dataSource.group([{ field: "value" }]);
Try This one. !
| |
doc_23534405
|
try:
for i in list:
with open(i, 'r') as f:
json_data = json.load(f)
if something == some:
print("ddddddddddddddd")
else:
print("Check successful!!!")
except IOError:
print("exception")
i wuold block after print("dddddddd") how can i force the exit?
A: To exit a for or while loop, use the keyword break (docs). This works for "infinite" loops too (like the one below).
Example:
n = 0
while True:
print("Running")
if n == 3:
break
n += 1
will print:
Running
Running
Running
Running
(since it'll run when n is 0, 1, 2 and 3 -> 4 times)
| |
doc_23534406
|
it may be mapping twice so it shows wrong result.
$this->Inventory->find('all',array('joins'=>array(
array('table' => 'items',
'alias' => 'item',
'type' => 'left',
'conditions' => array(
'Inventory.item_id = item.id')
),
array('table' => 'material_owners',
'alias' => 'owner',
'type' => 'left',
'conditions' => array(
'Inventory.material_owner_id = owner.id')
),
array('table' => 'projects',
'alias' => 'project',
'type' => 'left',
'conditions' => array(
'Inventory.project_id = project.id')
),
array('table' => 'material_payments',
'alias' => 'mp',
'type' => 'left',
'conditions' => array(
'Inventory.material_owner_id=mp.material_owner_id'),
),
),
'conditions'=>array('Inventory.project_id'=>$project_id),
'fields' =>array('sum(Inventory.total_amount) as total_amount','sum(mp.paid_amount) as paid_amount','item.name','item.id','owner.id','owner.first_name','owner.last_name','project.id','project.name'),
'group'=> array('item.name','item.id','owner.id','owner.first_name','owner.last_name','project.name','project.id')
)
);
This is the result query generated by cakephp.
SELECT sum("Inventory"."total_amount") as total_amount, sum("mp"."paid_amount") as paid_amount, "item"."name" AS "item__name", "item"."id" AS "item__id", "owner"."id" AS "owner__id", "owner"."first_name" AS "owner__first_name", "owner"."last_name" AS "owner__last_name", "project"."id" AS "project__id", "project"."name" AS "project__name" FROM "inventories" AS "Inventory" left JOIN "items" AS "item" ON ("Inventory"."item_id" = "item"."id") left JOIN "material_owners" AS "owner" ON ("Inventory"."material_owner_id" = "owner"."id") left JOIN "projects" AS "project" ON ("Inventory"."project_id" = "project"."id") left JOIN "material_payments" AS "mp" ON ("Inventory"."material_owner_id" = "mp"."material_owner_id") LEFT JOIN "items" AS "Item" ON ("Inventory"."item_id" = "Item"."id") LEFT JOIN "units" AS "Unit" ON ("Inventory"."unit_id" = "Unit"."id") LEFT JOIN "projects" AS "Project" ON ("Inventory"."project_id" = "Project"."id") LEFT JOIN "material_owners" AS "MaterialOwner" ON ("Inventory"."project_id" = "MaterialOwner"."id") WHERE "Inventory"."project_id" = '4' GROUP BY "item"."name", "item"."id", "owner"."id", "owner"."first_name", "owner"."last_name", "project"."name", "project"."id"
A: I'm not sure what you're trying to achive here. Does your cake query work at all?
What errors do you get or how do you want the output to be?
For a sollution, I'd take a look at virtualfields.
http://book.cakephp.org/2.0/en/models/virtual-fields.html
They can be added to each model prior to your query with the joins.
| |
doc_23534407
|
The following is my code:
player.load([{
title: "test line",
sources: [
{
file: message.content,
provider: "${base}/resources/web/plugins/jwplayer6/HLSProvider6.swf",
type: "hls",
label: "240",
"default": true
},
{
file: message.content,
provider: "${base}/resources/web/plugins/jwplayer6/HLSProvider6.swf",
type: "hls",
label: "360"
}
]
}]);
player.play();
Can someone help me?
In addition:
I also want to know how to set hlslabel? What I set is useless.
A: I have use FlowPlayer instead of JWPlayer and it solved my problem.
| |
doc_23534408
|
Anyway I've been asked to adjust a few reports in Axys but haven't got a clue were to start. The Report Writing Language is like an amalgamation of (php, java, and cobalt) and not very nice to look at let alone make any scene of.
Was wondering if anyone here has any experience of this reporting soft ware as there isn't much documentation out there on it.
I just have to add in a few subtotal areas etc.
Here's a sample of the code to show you what I mean:
else
.#~9:face~$35:fname#~2_tmp3#~2_dtmp3#~2:llpri0#~2_dtmp7#~2_tmp7#~2_dtmp2#~2_dtmp6#~2_tmp10\n
if $:isbond "y" =*
.~~~$:bdesc\g
goto h end of row eval a
if $:mature "y" =$ $:iscash "n" =$ &
$_clip1 $<25:snmb
#_tmp3 #_dtmp3 #:adun #:valf * /
#subb4 #subb4 #_dtmp3 +~
#subb6 #subb6 #_dtmp7 +~
#_tmp7 #_dtmp2 #:adun #:valf * /
; .#_tmp7 #_dtmp2 #:adun #:valf * / \n
#subb8 #subb8 #_dtmp2 +~
#subb9 #subb9 #_dtmp6 +~
#_tmp10 #_dtmp5 #sub023 / 100 *
#subb14 #subb14 #_dtmp2 +~
#subb15 #subb15 #_dtmp3 +~
#subb16 #subb16 #_zero #_dtmp3 $:zeromv "y" =$ ? +~
#subb17 #subb17 #_zero #_dtmp2 $:zeromv "y" =$ ? +~
#subb19 #subb19 #_dtmp6 +~
#subb20 #subb20 #_dtmp7 +~
#subb21 #subb21 #_dtmp4 +~
#subb22 #subb22 #_dtmp5 +~
#subb23 #subb23 #_dtmp5 +~
#subb31 #_zero
#subb35 #subb35 #_dtmp7 +~
#subb39 #subb39 #_dtmp6 +~
if $nosymb "n" =*
.#~9:face~$_clip1~$35:fname#~2_tmp3#~2_dtmp3#~2:llpri0#~2_dtmp7#~2_tmp7#~2_dtmp2#~2_dtmp6#~2_tmp10\n
else
.#~9:face~$35:fname#~2_tmp3#~2_dtmp3#~2:llpri0#~2_dtmp7#~2_tmp7#~2_dtmp2#~2_dtmp6#~2_tmp10\n
if $:isbond "y" =*
.~~~$:bdesc\g
goto h end of row eval a
if $:mature "y" =$ $:isbond "y" =* $:iscurr "y" =* $:iscash "y" =* | $:vrs "y" =* &| &
#_dtmp0 #::llai0
#_dtmp1 #::rrai0
$_clip1 $<25:snmb
#subb4 #subb4 #_dtmp3 +~
#subb6 #subb6 #_dtmp7 +~
#subb8 #subb8 #_dtmp2 +~
#subb9 #subb9 #_dtmp6 +~
#_tmp10 #_dtmp5 #sub023 / 100 *
#subb11 #subb11 #_dtmp1 +~
#subb12 #subb12 #_dtmp0 +~
#subb14 #subb14 #_dtmp2 +~
#subb15 #subb15 #_dtmp3 +~
#subb16 #subb16 #_zero #_dtmp3 $:zeromv "y" =$ ? +~
#subb17 #subb17 #_zero #_dtmp2 $:zeromv "y" =$ ? +~
#subb19 #subb19 #_dtmp6 #_dtmp1 +~ +~
#subb20 #subb20 #_dtmp7 #_dtmp0 +~ +~
#subb21 #subb21 #_dtmp4 +~
#subb22 #subb22 #_dtmp5 +~
#subb23 #subb23 #_dtmp5 #_dtmp1 +~ +~
#subb31 #_zero
#subb35 #subb35 #_dtmp7 +~
#subb39 #subb39 #_dtmp6 +~
Any help or direction would be greatly appreciated.
A: I have found that the best way to understand Advent's replang is to generate/modify a new/existing report with the Report Writer (repwiz32.exe) and analyze the diff between the old & new files. The language is more like perl than anything else.
Here's the link to the latest ('14.2) Rep Lang PDF: https://www.dropbox.com/s/h17kpk86nuld16a/AdventReplang14.2.pdf?dl=0
Good luck.
| |
doc_23534409
|
mix.sass([
'file_1.scss',
'file_2.scss',
'file_n.scss'
], 'public/css/app.css');
In Laravel 5.4 this is not working. Is there a chance to do something similar in Laravel 5.4?
A: If you've upgraded to Laravel Mix along with 5.4 then the syntax has changed. You should now use Sass the expected way. Create an app.scss file as the entry to your stylesheet, then use the @import tag to import other stylesheets.
@import 'file_1.scss';
@import 'file_2.scss';
@import 'file_n.scss';
| |
doc_23534410
|
Here is my GcmBroadcastReceiver:
public class GcmBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private MessageDatabaseHelper MDH;
Context ctx;
@Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
try {
sendNotification("Send error: " + intent.getExtras().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
try {
sendNotification("Deleted messages on server: " +
intent.getExtras().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
if(intent.getExtras().getString("message") != null){
sendNotification(intent.getExtras().getString("message"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) throws JSONException {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
SharedPreferences prefs1 = ctx.getSharedPreferences("UNIQUE", Context.MODE_PRIVATE);
int unique_id = prefs1.getInt("UNIQUE_ID", 0);
SharedPreferences.Editor editor = prefs1.edit();
unique_id++;
editor.putInt("UNIQUE_ID", unique_id);
editor.commit();
Log.v("TEST", "sharedprefs - " + prefs1.getInt("UNIQUE_ID", 0));
JSONObject JSdata = new JSONObject(msg);
String category = "";
String text = "";
String subject = "";
String from = "";
if(JSdata.getString("Category") != null){
Log.v("TEST", "CATEGORY - " + JSdata.getString("Category"));
category = JSdata.getString("Category");
}
if(JSdata.getString("Subject") != null){
Log.v("TEST", "SUBJECT - " + JSdata.getString("Subject"));
subject = JSdata.getString("Subject");
}
if(JSdata.getString("Message") != null){
Log.v("TEST", "Message - " + JSdata.getString("Message"));
text = JSdata.getString("Message");
}
if(JSdata.getString("From") != null){
Log.v("TEST", "FROM - " + JSdata.getString("From"));
from = JSdata.getString("From");
}
String dateTime = "";
Time now = new Time();
now.setToNow();
dateTime = (now.month + 1) + "/" + now.monthDay + " " + now.hour + ":" + now.minute;
Log.v("date", "date - " + dateTime);
Message message = new Message(1, category, text, subject, from, dateTime);
MDH = new MessageDatabaseHelper(ctx);
MDH.addMessage(message);
// new AsyncTask() {
// @Override
// protected String doInBackground(Object... arg0) {
// Intent mainIntent = new Intent(ctx, MainActivity.class);
// mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ctx.startActivity(mainIntent);
// Log.v("GCMDEMO", "background");
// return "";
// }
// }.execute(null, null, null);
Intent gcmIntent = new Intent(ctx, MessageActivity.class);
gcmIntent.putExtra("message1", message);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, unique_id,
gcmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Choice Cloud Notification")
.setContentText(JSdata.getString("Subject") + " " + JSdata.getString("Category"))
.setAutoCancel(true);
NotificationCompat.InboxStyle big = new NotificationCompat.InboxStyle(
mBuilder);
big.setSummaryText(JSdata.getString("Subject") + " " + JSdata.getString("Category"));
big.addLine(JSdata.getString("Message"));
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(unique_id, big.build());
//mBuilder.setContentIntent(contentIntent);
//mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
And here is my MainActivity
public class MainActivity extends Activity{
private MessageDatabaseHelper MDH;
private boolean initialLaunch = false;
private StableArrayAdapter adapter;
private ListView listview;
private List<Message> mList;
private Spinner spinner;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String SENDER_ID = "469307705305"; //This is the project number under the API
static final String TAG = "GCMDemo";
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
regid = getRegistrationId(context);
if (regid.length() == 0) {
registerBackground();
}
gcm = GoogleCloudMessaging.getInstance(this);
spinner = (Spinner) findViewById(R.id.category_spinner);
MDH = new MessageDatabaseHelper(this);
//On first launch of app, add some mock messages for testing
if(isInitialLaunch()){
setInitialLaunch(true);
Message m1 = new Message(1, "RateCenter", "rates are low", "Sub1", "From1", "7/31 8:45");
MDH.addMessage(m1);
SharedPreferences prefs1 = getSharedPreferences("UNIQUE", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs1.edit();
editor.putInt("UNIQUE_ID", 0);
editor.commit();
}
//Message m1 = new Message(1, "RateCenter", "rates are low", "Sub1", "From1");
//MDH.addMessage(m1);
//Grab all categories dynamically from database
List<String> cList = new ArrayList<String>();
cList = MDH.getAllCategories();
HashSet hs = new HashSet();
hs.addAll(cList);
cList.clear();
cList.addAll(hs);
//Add those categories to arraylist for use in spinner
List<String> categories = new ArrayList<String>();
//categories.add("Please select a category");
categories.add("All");
for(String s:cList){
categories.add(s);
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
// Specify the layout to use when the list of choices appears
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter1);
//add onitemselected listener to spinner
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
//Refresh main activity with correct set of messages pertaining to category selected
String test1 = parent.getItemAtPosition(pos).toString();
String test2 = MyApplication.globalCategory;
if(!(test1.equals(test2))){
MyApplication.sPos = pos;
MyApplication.globalCategory = parent.getItemAtPosition(pos).toString();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}});
//Creates a listview to be used to store messages
listview = (ListView) findViewById(R.id.list);
listview.setItemsCanFocus(false);
//grab messages from database for use in listview corresponding to category selected
mList = new ArrayList<Message>();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
}
//instantiates adapter and adds it to listview
adapter = new StableArrayAdapter(this, mList);
listview.setAdapter(adapter);
listview.setClickable(true);
//adds click listener to list
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Log.v("GCMDemo", "Registration id is - " + getRegistrationId(MainActivity.this));
Message clickedMessage = (Message)parent.getItemAtPosition(position);
clickedMessage.setUnread(false);
MDH.updateUnread(clickedMessage);
//starts new messageactivity, passing the message clicked on as an extra to the intent
listview.invalidateViews();
Intent startMessageActivityIntent = new Intent();
startMessageActivityIntent.putExtra("message1", clickedMessage);
startMessageActivityIntent.setClass(MainActivity.this,
MessageActivity.class);
startActivity(startMessageActivityIntent);
finish();
}
});
}
@SuppressWarnings("unchecked")
private void registerBackground() {
new AsyncTask() {
@Override
protected String doInBackground(Object... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// Save the regid - no need to register again.
setRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
Log.v("GCMDEMO", "GCMWHAT - " + msg);
return msg;
}
}.execute(null, null, null);
}
private void setRegistrationId(Context context, String regid) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regid);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.length() == 0) {
Log.v(TAG, "Registration not found.");
return "";
}
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.v(TAG, "App version changed");
return "";
}
return registrationId;
}
private int getAppVersion(Context context2) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGCMPreferences(Context context2) {
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private class StableArrayAdapter extends ArrayAdapter<Message> {
//adapter class for use with listview, maps items to positions
//HashMap<Message, Integer> hMap = new HashMap<Message, Integer>();
private final Context context1;
private final List<Message> adaptList;
public StableArrayAdapter(Context cont,
List<Message> objects) {
super(context, R.layout.ccm_list_item, objects);
//for (int i = 0; i < objects.size(); i++) {
// hMap.put(objects.get(i), i);
//}
this.context1 = cont;
this.adaptList = new ArrayList<Message>();
this.adaptList.addAll(objects);
}
private class ViewHolder {
public TextView text;
public TextView text2;
public TextView textTime;
public CheckBox checkBox;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.ccm_list_item, null);
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder.text = (TextView) convertView.findViewById(R.id.rowText);
holder.text2 = (TextView) convertView.findViewById(R.id.rowText2);
holder.textTime = (TextView) convertView.findViewById(R.id.rowTextTime);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.listCheck);
holder.checkBox.setFocusable(false);
holder.checkBox.setFocusableInTouchMode(false);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Message message = (Message)cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
//country.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
int count = 0;
Message m1 = new Message();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
for (Message m: mList) {
if(count == position){
m1 = m;
}
count++;
}
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
for (Message m: mList) {
if(count == position){
m1 = m;
}
count++;
}
}
if (m1.getUnread() == false) {
holder.text.setText(m1.toString());
holder.text2.setText(m1.getText());
holder.textTime.setText(m1.getTime());
convertView.setBackgroundColor(Color.LTGRAY);
} else {
holder.text.setText(m1.toString());
holder.text2.setText(m1.getText());
holder.textTime.setText(m1.getTime());
convertView.setBackgroundColor(Color.WHITE);
holder.text.setTypeface(null, Typeface.BOLD);
holder.text2.setTypeface(null, Typeface.BOLD);
}
holder.checkBox.setFocusable(false);
holder.checkBox.setFocusableInTouchMode(false);
holder.text.setFocusable(false);
holder.text.setFocusableInTouchMode(false);
((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
return convertView;
}
}
public void setInitialLaunch(boolean initialLaunch) {
SharedPreferences settings = getSharedPreferences("APPLAUNCH", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("APPLAUNCHKEY", false);
editor.commit();
this.initialLaunch = initialLaunch;
}
public boolean isInitialLaunch() {
SharedPreferences settings = getSharedPreferences("APPLAUNCH", 0);
this.initialLaunch = settings.getBoolean("APPLAUNCHKEY", true);
return initialLaunch;
}
@Override
protected void onStart() {
//on start, grabs message from database and updates adapter with changes to data
super.onStart();
if(MyApplication.globalCategory.equals("All")){
mList = MDH.getAllMessages();
for (Message m: mList) {
}
}
else {
mList = MDH.getMessagesWithCategory(MyApplication.globalCategory);
for (Message m: mList) {
}
}
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged() ;
}
});
spinner.setSelection(MyApplication.sPos);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu);
return true;
}
//option item about added to menu and starts aboutactivity when selected
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Intent startActivityIntent = new Intent(this,
AboutActivity.class);
startActivity(startActivityIntent);
return true;
}
return true;
}
}
| |
doc_23534411
|
Here is my settings.py:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'bootstrap3',
'djangobower',
'social_auth',
)
AUTHENTICATION_BACKENDS = (
'social_auth.backends.google.GoogleOAuth2Backend',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
GOOGLE_OAUTH2_CLIENT_ID = 'CLIENT_ID'
GOOGLE_OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET'
SOCIAL_AUTH_USER_MODEL = 'auth.User'
SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'
GOOGLE_WHITE_LISTED_DOMAINS = ['google.com']
SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
'access_type': 'offline',
'approval_prompt': 'select_account+consent',
'prompt' : 'select_account+consent'
}
login.html:
{% load bootstrap3 %}
{% load static %}
<link media="all" href="{% static 'bootstrap/dist/css/bootstrap.min.css' %}" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src='{% static 'bootstrap/dist/js/bootstrap.min.js' %}'></script>
{% load static %}
<script type="text/javascript" src='{% static 'jquery/jquery.js' %}'></script>
<link media="all" href="{% static 'dashboard.css' %}" type="text/css" rel="stylesheet"/>
<script src='{% static 'canvasjs/canvasjs.min.js' %}' type="text/javascript"></script>
<link rel="stylesheet" href="{% static 'signin.css' %}" />
{% if form.errors %}
<p text-align="center">Your username and password didn't match. Please try again. {{form.errors}} </p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}" class="form-signin" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">ABC Website</h2>
<input id="id_username" maxlength="254" name="username" type="text" class="form-control" placeholder="Username" autofocus/>
<input id="id_password" name="password" type="password" class="form-control" placeholder="Password"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">System Account LogIn</button>
<input type="hidden" name="next" value="{{ next }}" />
</form>
<p style="text-align: center"><a href="{% url "socialauth_begin" "google-oauth2" %}?prompt=select_account+consent">GMail Login</a></p>
urls.py:
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', login_required(views.logout_view), name = "logout"),
url(r'^complete/(?P<backend>[^/]+)/$', views.AuthComplete.as_view()),
url(r'^login-error/$', views.LoginError.as_view(), 'login-error'),
url(r'', include('social_auth.urls')),
url(r'^admin/', include(admin.site.urls)),
A: In your html template you could have this within your login button to redirect to the same page:
href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}"
"next=" specifies where to link to next after logging in. So "next={{ request.path }}" links to the same path as the original request.
If you're just redirecting to the homepage then just use "next=/":
href="{% url 'social:begin' 'google-oauth2' %}?next=/"
A: What worked for me is to override get_context_data function
In the CBV do:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
next_page = self.request.GET.get('next')
context['next'] = next_page
return context
Then in the template:
href="{% url 'social:begin' 'google-oauth2' %}?next={{ next }}"
A: Add this to your settings.py file:
LOGIN_REDIRECT_URL = "/"
| |
doc_23534412
|
class Contact extends React.Component {
render() {
return (
<div id="authorization">
<h1>
{
if (this.state.authorized) {
'Contact'
} else {
'Enter the Password'
}
}
</h1>
)
}
}
As you can see in the above code, I have put a JS if-else code in between a pair of curly braces {}, because I read it on
Introducing JSX that
You can put any valid JavaScript expression inside the curly braces in JSX.
But the above code just didn't work. But if I replace it with a ternary operator:
<h1>
{ this.state.authorized ? 'Contact' : 'Enter the Password' }
</h1>
it works! Is that there are some situations under which I can only use ternary operator but not usual JS if-else statement?
A: A ternary expression is an expression. An if statement is a statement. A statement is not an expression.
The important difference here between an expression and a statement is that an expression returns a value.
A: If-else doesn't work in JSX, per the spec of the language: https://react-cn.github.io/react/tips/if-else-in-JSX.html
A: If you really what to do this, you could use an IIFE
Here is an example:
class Contact extends React.Component {
render() {
return (
<div id="authorization">
<h1>
{
(() => {
if (this.state.authorized) {
return 'Contact'
} else {
return 'Enter the Password'
}
})()
}
</h1>
)
}
}
But this is not standard, you are better off creating a variable before the return statement and adding it using a construct like this: { someVar }.
| |
doc_23534413
|
I'm looking for a way to provide researchers to access the same data in S3 via EMR notebooks for (a) generic R and Python scripts, and (b) Spark-enabled querying. But the proprietary solution and query language we have right now provides indexing and partitioning on an NFS store - so I want to preserve this functionality. I see that Delta Lake provides this, but I'm wondering if this can be achieved with simpler tools like Arrow.
A: You could use Delta lake to Partition a Parquet file. They are also indexed by default.
You can do it like this
%sql
CREATE TABLE UsableTable_unpartitioned
USING DELTA
LOCATION 'Location of the Parquet File on S3' ;
CREATE TABLE UsableTable
USING DELTA
PARTITIONED BY (my_partitioned_column)
LOCATION 'MyS3Location'
select * from UsableTable_unpartitioned;
DROP TABLE UsableTable_unpartitioned;
Verify your partitions and all the required information created :
%sql
describe detail UsableTable
You could expose this table using JDBC
| |
doc_23534414
|
Scanner s = new Scanner(System.in);
System.out.println("Enter grid size");
int t = s.nextInt(); // read number of elements
s.nextLine(); // consume new line
System.out.println("Enter the values");
int d = s.nextInt(); // read number of elements
s.nextLine();
String str[] = new String[t];
for(int k=0;k<t;k++) {
str[k]=s.nextLine();
}
Sample Output:
Enter grid size
3
Enter the values
123
234
456
A: Make sure that the length of all the strings inputted is the same, or else it will cause an error. While creating a 2D array, we have to specify the rows and columns. To get the column size, we try to find the length of the first string input.
Scanner in = new Scanner(System.in) ;
System.out.println("Enter grid size") ;
int size = in.nextInt() ; // size is the total number of incoming strings
String str = in.next() ;
int col = str.length() ; // getting the length of the fisrt string to get column size for the grid
char grid[][] = new char[size][col] ;
grid[0] = str.toCharArray() ;
for (int i = 1 ; i < size ; i++)
{
str = in.next() ;
grid[i] = str.toCharArray() ;
}
If you just need to read or go through (NOT edit/change) the characters of strings, you can use str.charAt(index) method. You won't need to create a 2D array char[][]
Hope this helps!
A: What you need, is "probably":
// so far so good...
// not: String str[] = new String[t];, but:
char [][] str = new char[t][];
for(int k=0;k<t;k++) {
str[k] = s.nextLine().toCharArray();
}
So:
*
*Change the type of str to char[t][].
*Set each str[k] to String.toCharArray(); (where String is s.nextLine()).
See javadoc: String.toCharArray()
| |
doc_23534415
|
like:
@Entity
@Table(name = "${fleet.table.name}")
public class Fleet {
...
}
I tried to find something but I didn't.
You can access external properties with the @Value("...") annotation.
So my question is: Is there any way I can configure the table names? Or can I change/intercept the query that is sent by hibernate?
Solution:
Ok, hibernate 5 works with the PhysicalNamingStrategy. So I created my own PhysicalNamingStrategy.
@Configuration
public class TableNameConfig{
@Value("${fleet.table.name}")
private String fleetTableName;
@Value("${visits.table.name}")
private String visitsTableName;
@Value("${route.table.name}")
private String routeTableName;
@Bean
public PhysicalNamingStrategyStandardImpl physicalNamingStrategyStandard(){
return new PhysicalNamingImpl();
}
class PhysicalNamingImpl extends PhysicalNamingStrategyStandardImpl {
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
switch (name.getText()) {
case "Fleet":
return new Identifier(fleetTableName, name.isQuoted());
case "Visits":
return new Identifier(visitsTableName, name.isQuoted());
case "Result":
return new Identifier(routeTableName, name.isQuoted());
default:
return super.toPhysicalTableName(name, context);
}
}
}
}
Also, this Stackoverflow article over NamingStrategy gave me the idea.
A: Table names are really coming from hibernate itself via its strategy interfaces. Boot configures this as SpringNamingStrategy and there were some changes in Boot 2.x how things can be customised. Worth to read gh-1525 where these changes were made. Configure Hibernate Naming Strategy has some more info.
There were some ideas to add some custom properties to configure SpringNamingStrategy but we went with allowing easier customisation of a whole strategy beans as that allows users to to whatever they need to do.
AFAIK, there's no direct way to do config like you asked but I'd assume that if you create your own strategy you can then auto-wire you own properties to there. As in those customised strategy interfaces you will see the entity name, you could reserve a keyspace in boot's configuration properties to this and match entity names.
mytables.naming.fleet.name=foobar
mytables.naming.othertable.name=xxx
Your configuration properties would take mytables and within that naming would be a Map. Then in your custom strategy it would simply be by checking from mapping table if you defined a custom name.
A: Spring boot solution:
Create below class
@Configuration
public class CustomPhysicalNamingStrategy extends SpringPhysicalNamingStrategy{
@Value("${table.name}")
private String tableName;
@Override
public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return Identifier.toIdentifier(tableName);
}
}
Add below property to application.properties:
spring.jpa.properties.hibernate.physical_naming_strategy=<package.name>.CustomPhysicalNamingStrategy
table.name=product
| |
doc_23534416
|
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
fputcsv($output, array('ID', 'Date', 'Status','Name'));
$rows = mysql_query('SELECT ID,post_date,post_status,post_name FROM wp_posts WHERE post_date LIKE "%2016-03-30%"');
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
And this is just a trail and here i only fetch data from post table.
But i need to connect to postmeta and other tables, so that i can get all information about order.
By searching on the internet i get the following code, but i don't know how to integrate with this with my code.
See the query for to get all order details:
select
p.ID as order_id,
p.post_date,
max( CASE WHEN pm.meta_key = '_billing_email' and p.ID = pm.post_id THEN pm.meta_value END ) as billing_email,
max( CASE WHEN pm.meta_key = '_billing_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_first_name,
max( CASE WHEN pm.meta_key = '_billing_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_last_name,
max( CASE WHEN pm.meta_key = '_billing_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_1,
max( CASE WHEN pm.meta_key = '_billing_address_2' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_2,
max( CASE WHEN pm.meta_key = '_billing_city' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_city,
max( CASE WHEN pm.meta_key = '_billing_state' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_state,
max( CASE WHEN pm.meta_key = '_billing_postcode' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_postcode,
max( CASE WHEN pm.meta_key = '_shipping_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_first_name,
max( CASE WHEN pm.meta_key = '_shipping_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_last_name,
max( CASE WHEN pm.meta_key = '_shipping_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_address_1,
max( CASE WHEN pm.meta_key = '_shipping_address_2' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_address_2,
max( CASE WHEN pm.meta_key = '_shipping_city' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_city,
max( CASE WHEN pm.meta_key = '_shipping_state' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_state,
max( CASE WHEN pm.meta_key = '_shipping_postcode' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_postcode,
max( CASE WHEN pm.meta_key = '_order_total' and p.ID = pm.post_id THEN pm.meta_value END ) as order_total,
max( CASE WHEN pm.meta_key = '_order_tax' and p.ID = pm.post_id THEN pm.meta_value END ) as order_tax,
max( CASE WHEN pm.meta_key = '_paid_date' and p.ID = pm.post_id THEN pm.meta_value END ) as paid_date,
( select group_concat( order_item_name separator '|' ) from wp_woocommerce_order_items where order_id = p.ID ) as order_items
from
wp_posts as p,
wp_postmeta as pm
where
post_type = 'shop_order' and
p.ID = pm.post_id and
post_date BETWEEN '2015-01-01' AND '2015-07-08'
and post_status = 'wc-completed'
group by
p.ID
Please help to complete this, or is there any good method rather than this?
I don't want to use plugins.
Currently i have a plugin, but that is working slow, that's why i making this page.
Please help to solve this issue .
A: From my own blog post, this is the format for the SQL to extract information from an EAV style table layout.
$reportQuery = "
SELECT
A.ID as order_id
, B.meta_value as b_first_name
, C.meta_value as b_last_name
, D.meta_value as b_address_1
, E.meta_value as b_address_2
, F.meta_value as b_country
, G.meta_value as b_state
, H.meta_value as b_city
, I.meta_value as b_postcode
, J.meta_value as b_user_id
, K.user_email as b_email
FROM wp_posts as A
LEFT JOIN wp_postmeta B
ON A.id = B.post_id AND B.meta_key = '_billing_first_name'
LEFT JOIN wp_postmeta C
ON A.id = C.post_id AND C.meta_key = '_billing_last_name'
LEFT JOIN wp_postmeta D
ON A.id = D.post_id AND D.meta_key = '_billing_address_1'
LEFT JOIN wp_postmeta E
ON A.id = E.post_id AND E.meta_key = '_billing_address_2'
LEFT JOIN wp_postmeta F
ON A.id = F.post_id AND F.meta_key = '_billing_country'
LEFT JOIN wp_postmeta G
ON A.id = G.post_id AND G.meta_key = '_billing_state'
LEFT JOIN wp_postmeta H
ON A.id = H.post_id AND H.meta_key = '_billing_city'
LEFT JOIN wp_postmeta I
ON A.id = I.post_id AND I.meta_key = '_billing_postcode'
LEFT JOIN wp_postmeta J
ON A.id = J.post_id AND J.meta_key = '_customer_user'
LEFT JOIN wp_users K
ON J.meta_value = K.ID
WHERE A.post_type = 'shop_order'
AND A.post_status = 'wc-completed';
AND A.post_date_gmt >= DATE_SUB(NOW(), INTERVAL 1 DAY)
";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=woocommerce-'.date('Y-m-d').'.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
$rows = mysql_query($reportQuery);
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);
| |
doc_23534417
|
This is my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.0)
project(TEST)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_PREFIX_PATH "/opt/Qt/Qt5.8.0")
set(QT_QMAKE_EXECUTABLE ${CMAKE_PREFIX_PATH}/5.8/clang_64/bin/qmake)
find_package(Qt5Widgets)
...
This is the error message I get:
CMake Warning at CMakeLists.txt:56 (find_package):
By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project
has asked CMake to find a package configuration file provided by
"Qt5Widgets", but CMake did not find one.
Could not find a package configuration file provided by "Qt5Widgets" with
any of the following names:
Qt5WidgetsConfig.cmake
qt5widgets-config.cmake
Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set
"Qt5Widgets_DIR" to a directory containing one of the above files. If
"Qt5Widgets" provides a separate development package or SDK, be sure it has
been installed.
I followed what written in Qt documentation, so I do not understand what is wrong.
Version details:
- cmake 3.9.0
- Qt 5.8.0
- QMake 3.1
- Mac OS X 10.9.5
A: Did you check CMake version that is compatible with QT? Also did you check that everything is ok with qmake? Because this is what causes the problems most of the times. Check QT_QMAKE_EXECUTABLE to be pointing in the new QT version, i get problems with new versions of QT all the time.
A: Fixed setting the following system variables:
QTDIR=/opt/Qt/Qt5.8.0/5.8/clang_64
PATH=$PATH:/opt/Qt/Qt5.8.0/5.8/clang_64/bin
and removing:
set(CMAKE_PREFIX_PATH "/opt/Qt/Qt5.8.0")
from CMakeLists.txt.
| |
doc_23534418
|
I need to get an instance from a private static nested class, derived from an instance of the surrounding superclass.
Given you have these (simplified) nested Java classes
public abstract class GLFWKeyCallback extends Callback implements GLFWKeyCallbackI {
public static GLFWKeyCallback create(GLFWKeyCallbackI instance) {
new Container(instance.address(), instance);
}
private static final class Container extends GLFWKeyCallback {
private final GLFWKeyCallbackI delegate;
Container(long functionPointer, GLFWKeyCallbackI delegate) {
super(functionPointer);
this.delegate = delegate;
}
}
}
I get back a Container instance as a GLFWKeyCallback, by way of another external method. You can think of this method as:
public static GLFWKeyCallback getCallback() {
return GLFWKeyCallback.create(anInternalInstance)
}
in Kotlin:
val callback:GLFWKeyCallback = getCallback()
// I would now want to cast,
// or in other ways use callback
// as the GLFWKeyCallback.Container class it actually is.
val callbackAsContainer = callback as GLFWKeyCallback.Container // Error: Container is private
val ContainerClass = GLFWKeyCallback::class.nestedClasses.find { it.simpleName?.contains("Container") ?: false }!!
// Gives me a KClass<*> that I don't know how to use, can't find documentation for this kind of circumstance
// If using the class instance itself is not possible I would at least want to get the
// Container.delegate of GLFWKeyCallbackI
val delegateField = ContainerClass.memberProperties.findLast { it.name == "delegate" }!!
val fieldValue = field.get(callback)
// Error: Out-projected type 'KProperty1<out Any, Any?>' prohibits the use of 'public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1'
A: Why you don't want to use Java reflection? You can use it also from Kotlin:
val callback = getCallback()
val field = callback::class.java.getDeclaredField("delegate")
field.isAccessible = true
val delegate = field.get(callback) as GLFWKeyCallbackI
A: You can still get the class via .getClass(). This example prints '5':
public class Example {
public static void main(String[] args) throws Exception {
Object o = Target.get();
Field f = o.getClass().getDeclaredField("field");
f.setAccessible(true);
Integer i = (Integer) f.get(o);
System.out.println(i);
}
}
public class Target {
public static Object get() { return new Inner(); }
private static class Inner {
private int field = 5;
}
}
If you know precise names:
Class<?> c = Class.forName("com.foo.pkgof.Target$Inner");
c.getDeclaredField("field");
works. Note the dollar. That's the separator to use between 'outer' and 'inner'.
| |
doc_23534419
|
main.php:
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath' => dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..',
'name' => 'FeedStreem',
// preloading 'log' component
'preload' => array( 'log' ),
// autoloading model and component classes
'import' => array(
'application.models.*',
'application.components.*',
'application.controllers.*',
),
// application components
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=remote.host.com;dbname=dbnamehere',
'emulatePrepare' => true,
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
/*'enableProfiling' => true*/
),
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
),
'authManager' => array(
'class' => 'CDbAuthManager',
'connectionID' => 'db'
),
'urlManager' => array(
// omitted
),
'errorHandler' => array(
// use 'site/error' action to display errors
'errorAction' => 'site/error',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'trace, info, error, warning',
),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params' => array(
// this is used in contact page
'adminEmail' => 'webmaster@example.com',
),
);
dev.php:
<?php
return CMap::mergeArray(
require(dirname( __FILE__ ) . '/main.php'),
array(
'modules' => array(
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'SECRET',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters' => array( '127.0.0.1', '::1' ),
),
),
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=dbname2',
'emulatePrepare' => true,
'username' => 'username2',
'password' => 'password2',
'charset' => 'utf8',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'trace, info, error, warning',
),
// uncomment the following to show log messages on web pages
array(
'class' => 'CWebLogRoute',
),
),
),
),
)
);
However, when I use dev.php locally, I get the following error:
Warning: PDO::__construct() [pdo.--construct]: [2002] No connection could be made because the target machine actively (trying to connect via tcp://remote.host.com:3306) in C:\web_workspace\lib\yii\framework\db\CDbConnection.php on line 405
Which tells me the dev.php did not overwrite that 'db' config option. How can I make a config file that inherits from main.php but can overwrite options when I merge it?
A: As far as i see from source code it should overwrite your config:
public static function mergeArray($a,$b)
{
foreach($b as $k=>$v)
{
if(is_integer($k))
isset($a[$k]) ? $a[]=$v : $a[$k]=$v;
else if(is_array($v) && isset($a[$k]) && is_array($a[$k]))
$a[$k]=self::mergeArray($a[$k],$v);
else
$a[$k]=$v;
}
return $a;
}
Source: http://code.google.com/p/yii/source/browse/tags/1.1.8/framework/collections/CMap.php
Also official documentation says so:
If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive).
Source: http://www.yiiframework.com/doc/api/1.1/CMap#mergeArray-detail
Try to determine the problem via print_r the result array and look at it inner structure. I think the problem is here.
A: If your project involves (or will involve) more than 1 developer, server, or customized deployment/test you have to watch out for VCS problems. For us we found it best to import a separate db.php file in config/main.php:
'db'=>require(dirname(__FILE__).'/db.php'),
The db.php file is a copy of (or symbolic link to) either db-test.php or db-deploy.php and is ignored by our VCS, while the various db-*.php files created for individual users continue to be tracked by the VCS:
bzr add protected/config/db-*.php
bzr ignore protected/config/db.php
This allows individual developers to run the system on their home machine connected to localhost databases while maintaining the deployed system's link to the central db.
A: I apologize if Yii has evolved much since I tested it out, but as I recall, you need to kind of work around this issue. Here is a link which outlines a few methods of doing so. It may be worth checking around to see if things have improved.
Blog article on environment dependent configuration
If you work with a dev, staging, and production environment which are all separate and maintained via git/svn/something else, I find it's easiest to ignore certain config files with frameworks that ignore environment settings. You have to make changes manually across these files at times, but this isn't a hardship as config files tend to remain similar once an app or website is established. This way you can tailor your settings for your environment for better debugging and testing on dev/staging, and otherwise better performance and no debugging on production.
A: How are you determining which config file to use? With a switch statement like Steve linked to?
I use an if statement in my index.php to decide which config file to use based on the server environment (as mentioned in the article Steve linked). It seems to work fine for me.
Also remember that if you are running a console application, you need to tell it to use the right conig file in protected/yiic.php also (just like in index.php).
Another thing that may be happening is CMap::mergeArray might not be merging like you want. Again, it works for me, but perhaps when the arrays are merged it is overwriting the wrong DB config string (it's choosing the wrong one)?
One way to fix this would be to NOT have the DB creds in the main.php config file, and just have them in each inheriting file. So you will need an inheriting file for each environment, and no environment will run directly off of the main.php file. This way when the arrays are merged you will always have the right DB connection string.
Good luck!
A: I have 2 configuration files (development and production). May be you can try my configuration.
main.php
return array(
'name' => 'My Application',
'language' => 'id',
'charset' => 'utf-8',
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
// gii module
'modules' => array(
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'admin'
),
),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
// preloading 'log' component
'preload' => array('log'),
'defaultController' => 'site',
// application components
'components' => array(
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
'loginUrl' => array('user/login'),
),
'errorHandler' => array(
// use 'site/error' action to display errors
'errorAction' => 'site/error',
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>require('params.php'),
);
you can customize how to show the error log for your development and production server
development.php // you can customize the packages imported for development and production
return CMap::mergeArray(
array(
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=mydb',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
),
array(
'class' => 'CWebLogRoute',
),
array(
'class' => 'CDbLogRoute',
'levels' => 'trace, info, warning, error',
'connectionID' => 'db',
'autoCreateLogTable' => true,
),
),
),
),
),
require('main.php')
);
production.php
return CMap::mergeArray(
array(
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=myserver.com;dbname=mydb',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'mypassword',
'charset' => 'utf8',
'tablePrefix' => '',
),
'log' => array(
'class' => 'CLogRouter',
'routes' => array(
array(
'class' => 'CFileLogRoute',
'levels' => 'error, warning',
),
array(
'class' => 'CDbLogRoute',
'levels' => 'trace, info, warning, error',
'connectionID' => 'db',
'autoCreateLogTable' => true,
),
),
),
),
),
require('main.php')
);
just run the development or production configuration rather than main config
A: My problem was I was actually loading "index.php" when I wanted "index-dev.php".
My .htaccess redirect wasn't working for "localhost/" but it was working for "localhost/page".
I've got it working now by typing "localhost/index-dev.php
A: If you're using Yii you can also use the CMap::mergeArray function which does what the longer version of the accepted answer does already.
The last part of my index file looks like this:
$configMain = require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'main.php');
$configServer = require_once( dirname( __FILE__ ).DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'main' . $env . '.php' );
require_once($yii);
$config = CMap::mergeArray( $configMain, $configServer );
// Set Path alias for all javascript scripts
Yii::setPathOfAlias('js', dirname($_SERVER['SCRIPT_NAME']).DIRECTORY_SEPARATOR."js/");
Yii::createWebApplication($config)->run();
The part left out is at the top where I determine if I'm local or on the server.
| |
doc_23534420
|
I initially chose to use Quartz instead of OpenGL, because I need to display some basic shapes and I need to update them every 5 seconds, so I thought Quartz was better and easier.
I found out that I can't simply draw in a view, but I have to subclass a UIView and draw in the drawRect method.
In my project, the user should be able to pinch and zoom on graphics, so I planned to add a pinchgesture to the view, but I am doubtful about how to redraw everything after the pinch. Do I have to erase everything and re-add the subviews so the drawRect will trigger or is there a better way to do this?
Thanks a lot.
A: When using Quartz, you technically don't have to subclass the view and replace the drawRect, but it probably is best practice. When you want to redraw your window, just call [self setNeedsDisplay]; (if calling from the subclassed view, or [self.view setNeedsDisplay]; if doing it from the view controller). This will result in calling your drawRect method for you and it takes care of everything for you.
See the setNeedsDisplay documentation for more information.
| |
doc_23534421
|
Following a quick guide, I've setup the push channel and I have an object with the interface methods ON_START, ON_MESSAGE and etc. I'm currently testing the interface using wscat which you can get from npm.
When I tried connecting to my service for the first time using wscat I was receiving a HTTP 500 error.
I wasn't sure why I was getting the 500 error, so I tried to access the URL via http and a web browser to see what was happening.
500 SAP Internal Server Error
ERROR: Cross-Site Request Forgery (XSRF) check has failed ! (termination: ABORT_MESSAGE_STATE)
I had seen these tokens also in use by Gateway services, so I had created a quick gateway service and sent a GET request with X-CSRF-Token: Fetch except the token that I get from this doesn't work when I attempt to use uri parameter sap-XSRF.
Going forward, I started to debug CL_APC_MANAGER function HANDLE_REQUEST to see if my request comes in at all. I also wanted to trace where the origin of the 500 error comes from. I've managed to trace it back to CL_APC_MANAGER method CHECK_XSRF.
METHOD check_xsrf.
DATA: lv_xsrf_token TYPE string.
*
* validate XSRF token
*
lv_xsrf_token = i_server->request->get_form_field( name = if_http_form_fields_sap=>sap_xsrf ).
IF lv_xsrf_token IS INITIAL.
lv_xsrf_token = i_server->request->get_header_field( name = if_http_form_fields_sap=>sap_xsrf ).
ENDIF.
IF lv_xsrf_token IS INITIAL.
r_successful = abap_false.
ELSE.
CALL METHOD i_server->validate_xsrf_token
EXPORTING
token = lv_xsrf_token
IMPORTING
successful = r_successful
EXCEPTIONS
token_not_found = 1
cookie_not_found = 2
internal_error = 3
called_by_public_service = 4
OTHERS = 5.
IF sy-subrc <> 0 OR abap_false = r_successful.
r_successful = abap_false.
ELSE.
r_successful = abap_true.
ENDIF.
ENDIF.
ENDMETHOD.
If I skip this check manually with the debugger, than I'm able to connect to my web-socket server without a problem.
However I'm not sure at all how I'm actually supposed to get this token before attempting to connect. I noticed the XSRF Tokens are saved in database table SECURITY_CONTEXT. The only problem is an entry is created in this table with the key I need to have after I attempt to connect. I need it before and I'm not sure what the procedure is for retrieving a token properly.
Is there anybody with previous experience using these that can shed some light? Thanks in advance.
EDIT I'm using Version 740 with Service Pack 4.
A: The "correct" way to do have the header generated correctly is by maintaining table APC_CROSS_ORIGIN (transaction SAPC_CROSS_ORIGIN).
WebSockets functionality was only released for customer use in 7.40SP5, which probably explains why you don't have that table in your system. I'd recommend using your workaround for now, until your system has been patched.
| |
doc_23534422
|
db.getCollection('dealers').aggregate([{ "$geoNear" : { "near" : { "type" : "Point" , "coordinates" : [ 22.937506 , -30.559482]} , "spherical" : true , "distanceField" : "distance" , "maxDistance" : 21000000 , "num" : 6}}, { "$match" : { "$and" : [ { "brands" : { "$in" : [ "starbucks"]}} , { "country" : "za"} , { "language" : "en"}]}},{ $group: { _id: null, count: { $sum: 1 } } }, { "$limit" : 6}]);
I have two environments, the two environments have the same data and the same indexes, but when I run the above query, I get the first environment 6 registers and for the another 3 registers.
I checked and they have the same mongoDB version, Do you have any ideas about that?
| |
doc_23534423
|
Controller
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PageController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}
public function about(){
return "Kanishka";
}
Im using appache on xampp. when i call this method http://localhost/laravel/public/about/ it goes to http://localhost/about and page displays
Object not found!
The requested URL was not found on this server. If you entered the URL
manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
but when I chage root route as Route::get('/','PageController@about'); it is working.
A: Do like this
Route::get('about', [ 'as' => 'page.about', 'uses' => 'PageController@about' ]);
And write functions with the get keyword. (getAbout)
Examples of Laravel routes
| |
doc_23534424
|
we've been using codehaus jackson already with spring MVC .what i wanted to achieve is not in an ajax call with @ResponseBody action, i'm thinking of a util method to convert list of Pojos to json array but after looking at examples and ObjectMapper class it seems there is no straight forward way to achieve it. they have created a class PojoMapper to do that.
public static String toJson(Object pojo, boolean prettyPrint)
throws JsonMappingException, JsonGenerationException, IOException {
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
if (prettyPrint) {
jg.useDefaultPrettyPrinter();
}
m.writeValue(jg, pojo);
return sw.toString();
}
i'm just wondering it that's the recommended way. on another examples they used a file, but i have no entention to use file but object.So am wondering if anybody can show the way.
thanks for reading this
A: You should just be able to do the following.
List<POJO> list = ...;
String json = new ObjectMapper().writeValueAsString(list);
If you a bidirectional parent/child relationship. Then you need to add annotations to inform Jackson of this relationship.
class Parent {
private Child child;
@JsonManagedReference
Child getChild() {return child;}
void setChild(Child child) {this.child = child;}
}
class Child {
private Parent parent;
@JsonBackReference
Parent getParent() {return parent;}
void setParent(Parent parent) {this.parent = parent;}
}
The above informs Jackson of the cyclical nature of the relationship and doesn't try to unfold the infinite cycle of references. This works for Jackson 1.6+. I've not had this problem before and I don't have Jackson on this machine and so haven't been able to test this properly.
You should also note that the documentation says that the parent cannot be a collection.
| |
doc_23534425
|
The problem is, when using a 50% width, even though it's using border-box, is not truly 50%.
a reduced test case:
JsFiddle
Code
*,
*:before,
*:after {
box-sizing: border-box;
}
.row {
zoom: 1;
&: before, &: after {
content: "";
display: table;
}
&:after {
clear: both;
}
}
.half {
width: 50%;
padding: 10px;
}
.no-pad {
padding: 0;
}
.column {
float: left;
}
img {
max-width: 100%;
height: 100%;
display: block;
}
.eq-height-container {
display: flex;
}
.eq-height-column {
flex: 1;
}
<div class="row eq-height-container">
<div class="column half eq-height-column" style="background-color: red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa necessitatibus qui ea, quasi pariatur sed esse beatae porro in temporibus ipsum delectus, quisquam. Saepe sapiente, facere repellat tenetur quae aut.</p>
</div>
<div class="column half no-pad eq-height-column">
<img src="http://lorempixel.com/400/200" alt="">
</div>
</div>
<div class="row eq-height-container">
<div class="column half no-pad eq-height-column">
<img src="http://lorempixel.com/400/200" alt="">
</div>
<div class="column half eq-height-column" style="background-color: red;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa necessitatibus qui ea, quasi pariatur sed esse beatae porro in temporibus ipsum delectus, quisquam. Saepe sapiente, facere repellat tenetur quae aut.</p>
</div>
</div>
Is there a simple way around this?
A: That's because you're mixing in flex. If you remove .eq-height-column you'll see that the two columns become the same width.
A: you can set img to width:100% and remove flex:1 and float:left as well if you want to keep display:flex for equal height
body {
margin: 0
}
*,
*:before,
*:after {
box-sizing: border-box;
}
.row::before,
.row::after {
content: "";
display: table;
}
.row::after {
clear: both;
}
.half {
width: 50%;
padding: 10px;
background: red
}
.no-pad {
padding: 0;
}
img {
width: 100%;
height: 100%;
display: block;
}
.eq-height-container {
display: flex;
}
.eq-height-column {
/* flex: 1;*/
}
<div class="row eq-height-container">
<div class="column half eq-height-column">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa necessitatibus qui ea, quasi pariatur sed esse beatae porro in temporibus ipsum delectus, quisquam. Saepe sapiente, facere repellat tenetur quae aut.</p>
</div>
<div class="column half no-pad eq-height-column">
<img src="//lorempixel.com/400/200" alt="">
</div>
</div>
<div class="row eq-height-container">
<div class="column half no-pad eq-height-column">
<img src="//lorempixel.com/400/200" alt="">
</div>
<div class="column half eq-height-column">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa necessitatibus qui ea, quasi pariatur sed esse beatae porro in temporibus ipsum delectus, quisquam. Saepe sapiente, facere repellat tenetur quae aut.</p>
</div>
</div>
| |
doc_23534426
|
.nav-dropdown-items {
.nav-link {
padding-left: 1rem;
.nav-dropdown-items {
.nav-link {
padding-left: 2rem;
.....
}
}
}
}
This is my sass code
@mixin generatePadding($counter, $i:1){
@debug $i;
@debug $counter;
.nav-dropdown-items {
.nav-link {
padding-left: 1rem + $i;
@if $i < $counter {
@debug "include";
@include generatePadding($counter, ($i+1)); // next iteration
}
}
}
}
But the padding is always the same(2rem) instead 2rem, 3rem, 4rem, ....
Someone can tell me why?
A: I have tested your code in https://www.sassmeister.com/ and just added @include generatePadding(3); at the end of it. It's result is:
.nav-dropdown-items .nav-link {
padding-left: 2rem;
}
.nav-dropdown-items .nav-link .nav-dropdown-items .nav-link {
padding-left: 3rem;
}
.nav-dropdown-items .nav-link .nav-dropdown-items .nav-link .nav-dropdown-items .nav-link {
padding-left: 4rem;
}
Everything seems to be good. Also please make sure your sass compiler work properly.
| |
doc_23534427
|
$(document).ready(function(e){
var i = 10;
var fontsize;
function pulseLoop() {
fontsize = (Math.sin(i) * 10) + 50;
$(".changer-container").css("font-size",fontsize + "px");
i = i + .5;
setTimeout(pulseLoop, 100);
}
pulseLoop();
$(document).focus();
});
http://jsfiddle.net/MdQxh/2/
A: You need to adjust the timeout duration.
100 ms is equivalent to 10fps (calculated by 1000/100).
To appear smooth, you need at least 24-30 fps, so set the delay to at least 40ms or 30ms or (even 16ms for 60fps) to get a smooth animation.
That's why you see the animation as choppy.
Here's your fiddle at 60fps, I changed the i increment from i = i + .5; to i = i + .2; : http://jsfiddle.net/amyamy86/mecPv/
| |
doc_23534428
|
I want to use that program in loop and I want to use python to create that loop.
A: You need to import a connection between python and the JVM for running java commands.
Then you can create classes and call methods and get the returns like normal.
from py4j.java_gateway import JavaGateway # Import JVM-Connector
java_gateway = JavaGateway() # Connect to the JVM
java_TestClass = gateway.jvm.<Package>.Test() # Initalize a Class
result = java_TestClass.doSomethingWithReturn() # Call a method with return
java_TestClass.doSomethingElse("hello world") # Call void-Methhod
# Invoke static methods
java_gateway.jvm.java.lang.System.out.println('Hello World!')
For using a compiled .jar you need to import this, too.
import os
os.system("java -jar MyJar.jar")
| |
doc_23534429
|
FbCommand cmd = GetSomeCommandFromTheEther();
FbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
DoSomethingWith(reader);
else
TellTheUserWeGotNothing();
What I've now learned is that FbDataReader.HasRows always returns True. In fact looking at the source code it would appear it is just a wrapper for FbDataReader.command.IsSelectCommand, not only useless, it makes the property name "HasRows" a complete misnomer.
In any event, how can I find out whether a given query has rows, without advancing the record pointer? Note that I want to pass the reader off to an external service; if I call FbDataReader.Read() to check its result, I will consume a row and DoSomethingWith() will not get this first row.
A: I am afraid you have stumbled on a Firebird limitation. As stated in following Firebird FAQ link:
Why FbDataReader.HasRows returns always true?
The FbDataReader.HasRows property is implemented for compatibility
only. It returns always true because Firebird doesn't have a way for
know if a query returns rows of not without fetching the data.
There is already a mention of this in the Firebird Tracker. Check the issue DNET-305.
On the other hand, in .NET, it seems OleDbDataReader and SqlDataReader, which inherit from DbDataReader have the same problem, as stated in this MSDN link.
Since FbDataReader inherits from the same class as those, you might want to consider one of the workarounds that Microsoft suggests in its MSDN article, which is to perform first a select count(*). Granted, that is unelegant and a waste of time and resources but at least it could help you out.
| |
doc_23534430
|
{
"video":{
"local_recording_device":{
"codecs":null
},
"preferred_string":"___PREFERRED___",
"streams":{
"99176901":{
"id":"99176901",
"name":"PTZ Camera",
"site":"someone",
"email":"someone@awebsite.com",
"codec":"VP8 HD1 (720p)",
"local":true,
"screen":false,
"fit_to_window":true,
"stay_on_top":false,
"layout":0,
"native_width":1280,
"native_height":720,
"window_width":456,
"window_height":254,
"preferred":false,
"local_recording":false,
"device_id":"MJPEG Camera",
"normalized_device_id":"MJPEGCamera",
"shared_window_id":"MJPEG Camera",
"enable":true,
"big_location":"2",
"x":347,
"y":737,
"window_id":"197302",
"camera_id":null
},
"3091494011":{
"id":"3091494011",
"name":"Logitech Webcam C930e",
"site":"Joe Smith",
"email":"joe@awebsite.com",
"codec":"VP8 Medium (CIF)",
"local":false,
"screen":false,
"fit_to_window":true,
"stay_on_top":false,
"layout":0,
"native_width":352,
"native_height":288,
"window_width":864,
"window_height":702,
"preferred":true,
"local_recording":false,
"enable":true,
"big_location":"1",
"x":204,
"y":0,
"window_id":"197296",
"camera_id":null
},
"3798287599":{
"id":"3798287599",
"name":"Drive Camera",
"site":"ASiteName",
"email":"asitesame@awebsite.com",
"codec":"VP8 HD1 (720p)",
"local":true,
"screen":false,
"fit_to_window":true,
"stay_on_top":false,
"layout":0,
"native_width":1280,
"native_height":720,
"window_width":456,
"window_height":254,
"preferred":true,
"local_recording":false,
"device_id":"Logitech Webcam C930e",
"normalized_device_id":"LogitechWebcamC930e",
"shared_window_id":"Logitech Webcam C930e",
"enable":true,
"big_location":"3",
"x":814,
"y":737,
"window_id":"262822",
"camera_id":null
}
}
}
}
So, inside the JSON data is: "video", "streams" inside streams can be x amount of different streams (stream id's). The streams in "streams" (the long numbers) can change at anytime. In my example here there are three. I need to search through all streams in "streams" and see if any of them has a "email" that matches a particular email address. Each of the streams has a "email". If a email matches my supplied email address I need to check that streams "enable" to see if it's true or false.
Any help is appreciated in leading me in the right direction. I have not worked with a JSON data before.
A: You can use LINQ to JSON and SelectTokens to do the required query:
string json = GetJson();
var obj = JObject.Parse(json);
var testEmail = "someone@awebsite.com";
var streamQuery = obj.SelectTokens("video.streams.*").Where(s => (string)s["email"] == testEmail);
var firstEnabled = streamQuery.Select(s => (bool?)s["enable"]).FirstOrDefault();
The query returns a nullable bool that is true or false if the first stream for the desired email is enabled, or null if there is no stream for that email address.
Note that this returns the enabled state of the first stream matching the given email address. If you want to know if any are enabled, do:
var anyEnabled = streamQuery.Any(s => (bool)s["enable"]);
| |
doc_23534431
|
I have the below;
<a href="search-menu/{{data.id}}/{{data.name}}">
data.id & data.name are from ng-repeat
I've this function which makes sentence SEO friendly
slug = getSlug("Unfriendly Name");
console.log(slug); // Output: unfriendly-name
How can I use this in my href?
Something like;
<a href="search-menu/{{data.id}}/javascript:getSlug({{data.name}})">??
Thanks
A: instead of href use ng-href
<a ng-href="search-menu/{{data.id}}/getSlug(data.name)">
you can also make a function in your controller that will return the whole string.
<a ng-href="your wholeStringFunction(data.id, data.name)">
| |
doc_23534432
|
This line:
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
Size 85x85 is great for my Wildfire, but on HTC Desire it looks very small.
How can I change the image size according to the screen?
I have 2 different layouts, but Gridview hasn't any attribute in the XML files to change the image size.
A: You could try to make an adjustment based off the pixel density of the current device you are on.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
case DisplayMetrics.DENSITY_LOW:
imageView.setLayoutParams(new GridView.LayoutParams(lowVal, lowVal));
break;
case DisplayMetrics.DENSITY_MEDIUM:
imageView.setLayoutParams(new GridView.LayoutParams(medVal, medVal));
break;
case DisplayMetrics.DENSITY_HIGH:
imageView.setLayoutParams(new GridView.LayoutParams(highVal, highVal));
break;
}
A: Similar to willytate's answer, but you're better off creating a dimension value in an xml (for 85dp) and retrieving it like so:
int size = resources.getDimensionPixelSize(R.dimen.your_dimension);
That way, the width/height will be sized consistently, without you having to worry about much.
| |
doc_23534433
|
Bilinear Interpolation Device Function:
texture<float, cudaTextureType2D> tex32f;
//Device function
__device__ float blinterp(const float xIndex, const float yIndex)
{
//floor the coordinates to get to the nearest valid pixel
const int intX = static_cast<int>(xIndex);
const int intY = static_cast<int>(yIndex);
//Set weights of pixels according to distance from actual location
const float a = xIndex - intX;
const float b = yIndex - intY;
/* _____________________
*| | |
*|(1-a)(1-b)| (a)(1-b) |
*|__________|__________|
*| | |
*| (1-a)(b) | (a)(b) |
*|__________|__________|
*/
//Compute the weighted average of 4 nearest pixels
float out = (1 - a) * (1 - b) * tex2D(tex32f, intX,intY)
+ (a) * (1 - b) * tex2D(tex32f,intX + 1,intY)
+ (1 - a) * (b) * tex2D(tex32f, intX,intY + 1)
+ (a * b) * tex2D(tex32f,intX + 1,intY + 1);
return out;
}
Resize Kernel:
__global__ void kernel_resize(float* dst, int dstWidth, int dstHeight, int dstPitch, float xScale, float yScale)
{
const int xIndex = blockIdx.x * blockDim.x + threadIdx.x;
const int yIndex = blockIdx.y * blockDim.y + threadIdx.y;
if(xIndex>=dstWidth || yIndex>=dstHeight) return;
const unsigned int tid = yIndex * dstPitch + xIndex;
const float inXindex = xIndex * xScale;
const float inYindex = yIndex * yScale;
dst[tid] = blinterp(inXindex,inYindex);
}
Wrapper Function:
int resize_32f_c1(float* src,float* dst,int srcWidth,int srcHeight, int srcPitch, int dstWidth,int dstHeight,int dstPitch)
{
if((srcWidth == dstWidth) && (srcHeight == dstHeight))
{
cudaMemcpy2D(dst,dstPitch,src,srcPitch,srcWidth * sizeof(float),srcHeight,cudaMemcpyDeviceToDevice);
return 0;
}
cudaBindTexture2D(NULL,tex32f,src,srcWidth,srcHeight,srcPitch);
dim3 Block(16,16);
dim3 Grid((dstWidth + Block.x - 1)/Block.x, (dstHeight + Block.y - 1)/Block.y);
float x = (float)(srcWidth)/(float)dstWidth;
float y = (float)(srcHeight)/(float)dstHeight;
kernel_resize<<<Grid,Block>>>(dst,dstWidth,dstHeight,dstPitch/sizeof(float),x,y);
cudaUnbindTexture(tex32f);
return 0;
}
Results (Downscale by 2):
Input (10 x 10):
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
MATLAB and OpenCV Output:
0 0 0 0 0
0 0.25 0.5 0.25 0
0 0.5 1 0.5 0
0 0.25 0.5 0.25 0
0 0 0 0 0
My Output:
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0
A: Following the suggestion provided by @talonmies, I eventually found the cause of the problem.
When calculating the location of the pixel in the input image, the coordinates of the pixel should be pixel-centered, i.e an offset of 0.5 should be added to the calculated coordinates of the pixel. Not only this, the weights of the pixels should also be calculated using the pixel-centered coordinates. The coordinates of the pixel in the input image should be calculated as follows inside the kernel:
const float inXindex = xIndex * xScale + 0.5f;
const float inYindex = yIndex * yScale + 0.5f;
Alternatively, the blinterp function can be modfied as follows:
__device__ float blinterp(const float xIndex, const float yIndex)
{
//round the coordinates to get to the nearest valid pixel
const int intX = static_cast<int>(xIndex + 0.5f);
const int intY = static_cast<int>(yIndex + 0.5f);
//Set weights of pixels according to distance from actual location
const float a = xIndex - intX + 0.5f;
const float b = yIndex - intY + 0.5f;
.
.
.
| |
doc_23534434
|
x = 2
example = example2.replace("1", x)
I think its clear what I am looking for, I just have no clue how to do it.
A: My comments are based on Python v2.7:
In your code, "x" is assigned a integer value, they do not have replace method.
Instead, if "x" had carried normal string, then replace is available and this is how it works:
var2 = "palindrome syndrome"
print var2.replace("drome", "pal", 2)
Output:
palinpal synpal
In the statement, var2.replace, there are three arguments:
"drome" is the substring to find and replace with new string "pal" and do this for two occurrences of "drome".
| |
doc_23534435
|
[DataContract]
public class CoolStuff
{
[DataMember]
public Field[] CoolField { get; set; }
public CoolStuff()
{
CoolField = SetCoolField();
}
private Field[] SetCoolField()
{
return new Field[]
{
new Field("Project Information", "ProjectInformation"),
new Field("Resource Information", "ResourceInformation"),
}
}
}
[DataContract]
public class Field
{
[DataMember]
public string Prompt { get; set; }
[DataMember]
public string Value { get; set; }
[DataMember]
public bool IsLocked { get; set; }
public Field(string prompt, string value = "n/a", bool isLocked = false)
{
Prompt = prompt;
Value = value;
IsLocked = isLocked;
}
}
I call my constructors from a service, and this works fine and dandy when I try to serialize it with $.getJSON(/Service.svc/coolstuff/' + id, loadCoolStuff);
The problem is, when I make my Field class inherit from another class, that .getJson call fails without really giving me a reason why.
[DataContract]
public class CoolStuff
{
[DataMember]
public FieldBase[] CoolField { get; set; }
public CoolStuff()
{
CoolField = SetCoolField();
}
private FieldBase[] SetCoolField()
{
return new FieldBase[]
{
new Field("Project Information", "ProjectInformation"),
new Field("Resource Information", "ResourceInformation"),
}
}
}
[DataContract]
public class FieldBase
{
}
[DataContract]
public class Field : FieldBase
{
[DataMember]
public string Prompt { get; set; }
[DataMember]
public string Value { get; set; }
[DataMember]
public bool IsLocked { get; set; }
public Field(string prompt, string value = "n/a", bool isLocked = false)
{
Prompt = prompt;
Value = value;
IsLocked = isLocked;
}
}
Can someone please explain why with ^ this code, my call to .getJSON fails? I'm really stuck here. Thanks so much!
A: OK, reading between the lines I've deduced you're using WCF for this web service. The use of DataContract attributes and url ending in .svc make that clear enough. That's relevant, because this issue seems particular to the way WCF serializes. As mentioned in my above comments, the same class structure has no problems in ASP.NET Web API using the default Newtonsoft JSON serializer.
What you need here is the KnownType attribute to properly define derived types for serialization.
This article offers some straight-forward examples. This one has a bit more detail on the concepts.
For the example you've provided, you'd need to decorate the FieldBase definition like this:
[DataContract]
[KnownType(typeof(Field))]
public class FieldBase
{
}
Note that this will add an extra field to your JSON, like "__type":"Field:#MyTestWebProject". You could just ignore that, or go hunting for ways to get rid of it if it bothers you. I wouldn't guarantee it's possible though.
| |
doc_23534436
| ||
doc_23534437
|
My friend's web application runs a website with quite simple HTML to generate data for charts. I want to get certain values from a table on that page as he requires this information to be stored to a database.
So this is a part of the HTML table;
...
<tr>
<td width=30 align=center bgcolor=#006699 class=W><font color=white>1</font></td>
<td width=50 bgcolor=#FFFFFF align=center>7387</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>2</font></td>
<td width=50 bgcolor=#FFFFFF align=center>2881</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>3</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8782</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>4</font></td>
<td width=50 bgcolor=#FFFFFF align=center>5297</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>5</font></td>
<td width=50 bgcolor=#FFFFFF align=center>749</td>
</tr>
<tr>
<td align=center bgcolor=#006699 class=W><font color=white>6</font></td>
<td width=50 bgcolor=#FFFFFF align=center>3136</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>7</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8768</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>8</font></td>
<td width=50 bgcolor=#FFFFFF align=center>9548</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>9</font></td>
<td width=50 bgcolor=#FFFFFF align=center>6565</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>10</font></td>
<td width=50 bgcolor=#FFFFFF align=center>142</td>
</tr>
...
What I want to achieve is;
*
*I get two numbers - for example 1 and 8.
*My application checks the HTML of the page and selects the two td (as shown above) containing the numbers.
*Then, I have to get the value of the NEXT td.
The output of this would be 1=7387 and 8=9548.
I got stuck quite fast after trying to find the two td containing the given numbers.
My C# code so far;
using (WebClient webClient = new WebClient())
{
string completeHTMLCode = webClient.DownloadString("someUrl.php?getChartData=" + chartId);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(completeHTMLCode);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//td[@...]"))
{
}
}
Am I trying something impossible here?
A: I made a quick CsQuery sample how to accomplish this.
string file = File.ReadAllText("a.html"); // gets the html
CQ dom = file; // initializes csquery
CQ td = dom["td"]; // get all td files
td.Each((i,e) => { // go through each
if (e.FirstChild != null) // if element has child (font)
{
if (e.FirstChild.NodeType != NodeType.TEXT_NODE) // ignore text node
{
if (e.FirstChild.InnerText == "1") // if number is 1
{
Console.WriteLine(e.NextElementSibling.InnerText); // output the text
}
if (e.FirstChild.InnerText == "8") // etc etc
{
Console.WriteLine(e.NextElementSibling.InnerText);
}
}
}
});
Console.ReadKey();
A: You can just parse it into a dictionary and look it up that way. I could think of perhaps some better ways to parse it, but this does what you want.
void Main()
{
string html = @"<tr>
<td width=30 align=center bgcolor=#006699 class=W><font color=white>1</font></td>
<td width=50 bgcolor=#FFFFFF align=center>7387</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>2</font></td>
<td width=50 bgcolor=#FFFFFF align=center>2881</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>3</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8782</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>4</font></td>
<td width=50 bgcolor=#FFFFFF align=center>5297</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>5</font></td>
<td width=50 bgcolor=#FFFFFF align=center>749</td>
</tr>
<tr>
<td align=center bgcolor=#006699 class=W><font color=white>6</font></td>
<td width=50 bgcolor=#FFFFFF align=center>3136</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>7</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8768</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>8</font></td>
<td width=50 bgcolor=#FFFFFF align=center>9548</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>9</font></td>
<td width=50 bgcolor=#FFFFFF align=center>6565</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>10</font></td>
<td width=50 bgcolor=#FFFFFF align=center>142</td>
</tr>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
int[] nodes = doc.DocumentNode.SelectNodes("//td").Select ( dn =>
int.Parse(dn.InnerHtml.Contains("font") ? dn.FirstChild.InnerHtml : dn.InnerHtml)
).ToArray();
Dictionary<int,int> d = new Dictionary<int,int>();
for (int i = 0; i < nodes.Length; i+=2)
d.Add(nodes[i],nodes[i+1]);
d.Dump();
d[1].Dump();
d[8].Dump();
}
A: Well, if you only had this table data to work with it could be parsed using HTMLAgilityPack.
The first thing I'd do is do away with foreach to iterate through the tds, I'd use a counter, then use the counter id as an indexer. The code could look like this
for(int i = 1;i <= selectednodes.Count();i++)
{
if(selectednodes[i-1].InnerHtml.Contains("font")
{
if(selectednodes[i-1].FirstChild.Value == "1" || selectednodes[i-1].FirstChild.Value == "8")
{
myNodecollection.Add(selectednodes[i])
}
}
}
| |
doc_23534438
|
To complicate matters, I have a number of other editable controls, backed by CoreData, which do not need to resort to this behaviour.
I believe the solution to this problem revolves around the creation of a secondary Managed Object context, which I would use only for values edited within that particular NSTableView. But I'm confused as to how the two MOC would interact with each other.
What's the best solution to this problem?
A: The easiest solution would be to implement Core Data's undo functionality. That way you make the changes to Core Data but if the server returns the error, you just rollback the changes. See the Core Data docs for details.
| |
doc_23534439
|
Cache has an initial size, if you try inserting an item when cache is full last recently used item should be replaced...any ideas?
A: Have you looked at Guava ? It has factory-based methods for creating collections with caches etc.
e.g. (from the linked article)
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
A: On Android you can use http://developer.android.com/reference/android/util/LruCache.html. I quite sure that you can take that implementation from the AOSP and use it under the Apache License.
A: You can use a LinkedHashMap by implementing removeEldest
public static <K,V> Map<K,V> lruCache(final int maxSize) {
return new LinkedHashMap<K,V>(maxSize*4/3, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > maxSize;
}
};
}
For more details
http://vanillajava.blogspot.co.uk/2011/06/java-secret-lru-cache-in-java.html
http://blog.meschberger.ch/2008/10/linkedhashmaps-hidden-features.html
A: The most trivial approach would be to extend LinkedHashMap, override the removeEldestEntry(Map.Entry<K,V> eldest) method and decide in its implementation if your cache is "full" or not.
A: Look at LRUMap from Apache Commons.
A Map implementation with a fixed maximum size which removes the least recently used entry if an entry is added when full.
The least recently used algorithm works on the get and put operations only. Iteration of any kind, including setting the value by iteration, does not change the order. Queries such as containsKey and containsValue or access via views also do not change the order.
The map implements OrderedMap and entries may be queried using the bidirectional OrderedMapIterator. The order returned is least recently used to most recently used. Iterators from map views can also be cast to OrderedIterator if required.
All the available iterators can be reset back to the start by casting to ResettableIterator and calling reset().
Note that LRUMap is not synchronized and is not thread-safe. If you wish to use this map from multiple threads concurrently, you must use appropriate synchronization. The simplest approach is to wrap this map using Collections.synchronizedMap(Map). This class may throw NullPointerException's when accessed by concurrent threads.
A: You could keep a bound queue together with your hash map. In that way you would easily know which item is the oldest.
| |
doc_23534440
|
Is there a preferred or standardized way to run larger precanned scripts inside of c#?
PowerShell powershell = PowerShell.Create(RunspaceMode.NewRunspace);
PSCommand command = new PSCommand();
Collection<PSObject> psSessions = null;
command.AddCommand("Get-PSSession");
command.AddCommand("Remove-PSSession");
powershell.Commands = command;
psSessions = powershell.Invoke();
command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("AllowRedirection", true);
command.AddParameter("Authentication", "Kerberos");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", pconnectionURI);
command.AddParameter("Credential", Credential);
powershell.Commands = command;
psSessions = powershell.Invoke();
This is the multi line Powershell script below
try{
Get-Process -ProcessName Teams | Stop-Process -Force
Start-Sleep -Seconds 3
Write-Host "Teams Process Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing Teams Disk Cache" -ForegroundColor Yellow
try{
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\application cache\cache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\blob_storage" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\databases" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\cache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\gpucache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\Indexeddb" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\Local Storage" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\tmp" | Remove-Item -Confirm:$false
Write-Host "Teams Disk Cache Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Stopping Chrome Process" -ForegroundColor Yellow
try{
Get-Process -ProcessName Chrome| Stop-Process -Force
Start-Sleep -Seconds 3
Write-Host "Chrome Process Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing Chrome Cache" -ForegroundColor Yellow
try{
Get-ChildItem -Path $env:LOCALAPPDATA"\Google\Chrome\User Data\Default\Cache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:LOCALAPPDATA"\Google\Chrome\User Data\Default\Cookies" -File | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:LOCALAPPDATA"\Google\Chrome\User Data\Default\Web Data" -File | Remove-Item -Confirm:$false
Write-Host "Chrome Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Stopping IE Process" -ForegroundColor Yellow
try{
Get-Process -ProcessName MicrosoftEdge | Stop-Process -Force
Get-Process -ProcessName IExplore | Stop-Process -Force
Write-Host "Internet Explorer and Edge Processes Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing IE Cache" -ForegroundColor Yellow
try{
RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 8
RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 2
Write-Host "IE and Edge Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Cleanup Complete... Launching Teams" -ForegroundColor Green
Start-Process -FilePath $env:LOCALAPPDATA\Microsoft\Teams\current\Teams.exe
Stop-Process -Id $PID
}else{
Stop-Process -Id $PID
}
Edit 1/27/21 9am
I'm able to get this to work, I will try and figure out how to pass the credentials externally rather than hard coding them and try a larger and more complicated script now as well.
string script = @"$computerName = 'xxxx';
$user = 'xxxx\xxxx';
$pw = ConvertTo-SecureString -String 'xxxx' -AsPlainText -Force;
$creds = new-object -typename System.Management.Automation.PSCredential -ArgumentList $user, $pw;
Invoke-Command -ComputerName $computerName {get-childitem -path 'c:\'} -Credential $creds";
Edit 1/27/21 11am
The below works and will return the result of get-childitem with one issue, I'm getting an error message in addition to the folder results of. What's the fix for this error message?
"The input object cannot be bound to any parameters for the command
either because the command does not take pipeline input or the input
and its properties do not match any of the parameters that take
pipeline input."
// Credential is a c# object of System.Management.Automation.PSCredential
powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "extCreds");
powershell.AddParameter("Value", Credential);
powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "comp");
powershell.AddParameter("Value", "xxxx");
string script = @"$test1 = 'test1';
$test2 = 'test2';
$test3 = 'test3';
Invoke-Command -ComputerName $comp {get-childitem -path 'c:\'} -Credential $extCreds";
powershell.AddScript(script);
psSessions = powershell.Invoke();
| |
doc_23534441
|
It works fine on Android, but on iOS, it just shows a blank white screen.
Here's the debug output:
[INFO] 943E7E1BD31/Library/Application%20Support/Forge/assets-AA20D894-4614-43FB-BE67-D78F05175E9B/src/index.html
[DEBUG] Returning to javascript: {
[DEBUG] event = \"internal.connectionStateChange\";
[DEBUG] params = {
[DEBUG] connected = 1;
[DEBUG] wifi = 1;
[DEBUG] };
[DEBUG] }
[DEBUG] Native call: {
[DEBUG] callid = \"C812FD5E-EFAE-4BCD-A3EE-CFB2574F70EA\";
[DEBUG] method = \"internal.hideLaunchImage\";
[DEBUG] params = {
[DEBUG] };
[DEBUG] }
[DEBUG] Returning to
[DEBUG] script: {
[DEBUG] callid = \"C812FD5E-EFAE-4BCD-A3EE-CFB2574F70EA\";
[DEBUG] content = \"<null>\";
[DEBUG] status = success;
[DEBUG] }
After hiding launch image, it's calling content = \"<null>\"; ?
A: It turns out Sencha 2 has a bug, it was throwing an error like this:
Error: [ERROR][Ext.viewport.Ios#undefined] Timeout waiting for window.innerHeight to change
I did some research, and it seems to be a bug relating to Safari vs. UI Web View.
To solve this problem, add this under Ext.application({
viewport: { autoMaximize: false },
Cheers
| |
doc_23534442
|
I would like to declare the id of entity on class level and use it on each method. Here is the controller class:
@Controller
@RequestMapping(value="/job/{j_id}/instance")
public class JobController extends GenericController {
private final String htmlDir = "job/";
@RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(@PathVariable Long instance_id) {
ModelAndView result = new ModelAndView(htmlDir + "instance");
result.addObject("instance_id", instance_id);
Here I would like to use variable j_id from @RequestMapping
return result;
}
}
Can I achive this? Please help. Give me some code snippest please.
A: Have a try like this
@Controller
@RequestMapping(value="/job/{j_id}/instance")
public class JobController {
private final String htmlDir = "job/";
@RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(@PathVariable(value="j_id") Long instance_id) {
ModelAndView result = new ModelAndView(htmlDir + "instance");
result.addObject("instance_id", instance_id);
System.out.println("Instance Id -------------> " + instance_id);
return result;
}
}
Please notic "@PathVariable(value="j_id")"
To get both variables, you can change that line as following:
@RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(@PathVariable(value="j_id") Long jnstance_id, @PathVariable(value="i_id") Long instance_id) {
.....
}
| |
doc_23534443
|
Teams bean has few properties like Id, Name, Description, Location and list of Players.
Players bean has few properties like Id, Name, Age etc.
I have a service which returns the list of teams(JSON) and I want the output to return all the properties in Teams and only two properties in Players(Id and Name).
How can I serialize the TeamsList object in such a way that I have only two properties(Id, Name) in the resultant JSON
Currently using @AutoWired - which is returning all the properties of the Player object
Edit: There is a service which gives Individual Player details. I need the service to return the other data for that.
A: Use @JsonIgnore on the Player attributes you don't need.
| |
doc_23534444
|
$routes->add(
'index',
new Route('/', array('_controller' => 'indexAction'))
);
my "project" perfectly loads indexAction function, but if i try something like this
$routes->add(
'index',
new Route('/', array('_controller' => 'Test::indexAction'))
);
it says
Uncaught exception 'InvalidArgumentException' with message 'Class "Test" does not exist.'
But i cant find where must be my controllers, or how they must be included to be loaded successfully.
If this helps, at this moment i am using composer autoload with PSR-0 standart.
A: Like its said on the Symfony doc about routing, you have to
name your controller with this pattern :
bundle:controller:action
A: "Full" path solved the problem
new Route('/', array('_controller' => 'Levelup\\Controller\\Test::indexAction'))
Test::indexAction changed to Levelup\Controller\Test::indexAction
| |
doc_23534445
|
<SomeProperty>@(_AnotherProperty)</SomeProperty>
<SomeOtherProperty>$(_AnotherProperty)</SomeOtherProperty>
What's the difference between referencing _AnotherProperty with a @ versus a $?
A: Ok. So i think the answer is, they aren't both properties. Even though in the target files microsoft uses the same name.
The difference is $(Something) references a property.
Properties are name-value pairs that can be used to configure builds.
Properties are useful for passing values to tasks, evaluating
conditions, and storing values that will be referenced throughout the
project file. http://msdn.microsoft.com/en-us/library/ms171458.aspx
@(Something) references a "item."
MSBuild items are inputs into the build system, and they typically
represent files. Items are grouped into item types based on their
element names. Item types are named lists of items that can be used as
parameters for tasks. The tasks use the item values to perform the
steps of the build process. http://msdn.microsoft.com/en-us/library/ms171453.aspx
What was confusing me in the microsoft targets was the difference between a "Framework Directory" property, and a "Framework Directory Item". So I'll go on to learn further. I'm not going to make this as the answer just yet, in case others have a better response.
| |
doc_23534446
|
var gm = require('gm');
gm(infile)
.stroke("#000000")
.fill('#ffffff')
.font("./impact.ttf", 42)
.dither(false)
.drawText(0, 0, text, 'South')
.write(outfile, function (err) {
if (!err) {
console.log('Image processing done.');
}
else console.log(err);
});
It works fine, however a bit on the slow side. I think (or at least i hope) i can do better.
Now, that thing really translates to (i spied on gm):
$ convert /tmp/input.gif -stroke "#000000" -fill "#ffffff" \
-pointsize 42 -font ./impact.ttf \
-draw "gravity south text 0,0 SOME TEXT" \
-dither None output.gif
This takes about 30 seconds to process.
I've tried a few things:
*
*Adding -colors 128 shaves off around 7 seconds (but if the original .gif is 256 colors, some quality is lost).
*-coalesce adds 20 more seconds to the 30, no go.
The text is overlay on every frame, here's the final product (NOT the .gif i'm testing with - just a sample):
QUESTION #1
Is there anything i can do to make this faster, other than throw more compute at it? I'm open to lowering image quality.. but you know.. sensibly.
QUESTION #2
How would i go about getting some progress indicator in my frontend?
Can i listen for an event that has an approximate idea of how much data/time remains? An example would be fantastic.
Since all i'm doing is change a few pixels at the bottom on the input GIF, the live file size of input GIF vs resulting GIF is a pretty good indicator of how much time is left, but wondering if there's a better approach.
EDIT:
This is the GIF i'm testing with:
https://m.popkey.co/bca7ab/ygQJw.gif
$ identify -version
Version: ImageMagick 6.8.9-9 Q16 i686 2016-06-01 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules OpenMP
Delegates: bzlib cairo djvu fftw fontconfig freetype jbig jng jpeg lcms
lqr ltdl lzma openexr pangocairo png rsvg tiff wmf x xml zlib
A: I see you are running the Q16 version with 16-bit quantisation and that is probably overkill if you are happy with 128 colour GIFs anyway.
I got a 50% time reduction (albeit from 6s to 3s) on my desktop iMac by changing from the 16-bit to the 8-bit version. To get the 8-bit version, you need to rebuild using:
./configure --with-quantum-depth=8 ... your usual options...
Not only does that speed things up, but it also relieves "memory pressure" so it may help your application in other ways too by minimising paging.
You could also try adding in --enable-zero-configuration to prevent ImageMagick reading lots of XML config files at startup.
Some things run faster without OpenMP, so you could also consider disabling that when you run ./configure.
See also my comment about resources:
identify -list resource
and maybe increasing the memory available to ImageMagick using:
convert -limit memory 512MiB ....
As regards following progress, you could use -monitor like this:
convert -monitor anim.gif -stroke "#000000" -fill "#ffffff" -pointsize 42 -draw "gravity south text 0,0 'SOME TEXT'" -dither None output.gif
Sample Output
load image[anim.gif]: 1 of 2, 100% complete
load image[anim.gif]: 2 of 3, 100% complete
load image[anim.gif]: 3 of 4, 100% complete
load image[anim.gif]: 4 of 5, 100% complete
load image[anim.gif]: 5 of 6, 100% complete
load image[anim.gif]: 6 of 7, 100% complete
load image[anim.gif]: 7 of 8, 100% complete
load image[anim.gif]: 8 of 9, 100% complete
load image[anim.gif]: 9 of 10, 100% complete
load image[anim.gif]: 10 of 11, 100% complete
load image[anim.gif]: 11 of 12, 100% complete
load image[anim.gif]: 12 of 13, 100% complete
load image[anim.gif]: 13 of 14, 100% complete
load image[anim.gif]: 14 of 15, 100% complete
load image[anim.gif]: 15 of 16, 100% complete
load image[anim.gif]: 16 of 17, 100% complete
load image[anim.gif]: 17 of 18, 100% complete
load image[anim.gif]: 18 of 19, 100% complete
load image[anim.gif]: 19 of 20, 100% complete
load image[anim.gif]: 20 of 21, 100% complete
load image[anim.gif]: 21 of 22, 100% complete
load image[anim.gif]: 22 of 23, 100% complete
load image[anim.gif]: 23 of 24, 100% complete
load image[anim.gif]: 24 of 25, 100% complete
load image[anim.gif]: 25 of 26, 100% complete
load image[anim.gif]: 26 of 27, 100% complete
load image[anim.gif]: 27 of 28, 100% complete
load image[anim.gif]: 28 of 29, 100% complete
load image[anim.gif]: 29 of 30, 100% complete
load image[anim.gif]: 30 of 31, 100% complete
load image[anim.gif]: 31 of 32, 100% complete
load image[anim.gif]: 32 of 33, 100% complete
load image[anim.gif]: 33 of 34, 100% complete
load image[anim.gif]: 34 of 35, 100% complete
load image[anim.gif]: 35 of 36, 100% complete
load image[anim.gif]: 36 of 37, 100% complete
load image[anim.gif]: 37 of 38, 100% complete
load image[anim.gif]: 38 of 39, 100% complete
load image[anim.gif]: 39 of 40, 100% complete
load image[anim.gif]: 40 of 41, 100% complete
load image[anim.gif]: 41 of 42, 100% complete
load image[anim.gif]: 42 of 43, 100% complete
load image[anim.gif]: 43 of 44, 100% complete
load image[anim.gif]: 44 of 45, 100% complete
load image[anim.gif]: 45 of 46, 100% complete
load image[anim.gif]: 46 of 47, 100% complete
load image[anim.gif]: 47 of 48, 100% complete
load image[anim.gif]: 48 of 49, 100% complete
load image[anim.gif]: 49 of 50, 100% complete
load image[anim.gif]: 50 of 51, 100% complete
load image[anim.gif]: 51 of 52, 100% complete
load image[anim.gif]: 52 of 53, 100% complete
load image[anim.gif]: 53 of 54, 100% complete
load image[anim.gif]: 54 of 55, 100% complete
load image[anim.gif]: 55 of 56, 100% complete
load image[anim.gif]: 56 of 57, 100% complete
load image[anim.gif]: 57 of 58, 100% complete
load image[anim.gif]: 58 of 59, 100% complete
load image[anim.gif]: 59 of 60, 100% complete
load image[anim.gif]: 60 of 61, 100% complete
load image[anim.gif]: 61 of 62, 100% complete
load image[anim.gif]: 62 of 63, 100% complete
load image[anim.gif]: 63 of 64, 100% complete
load image[anim.gif]: 64 of 65, 100% complete
load image[anim.gif]: 65 of 66, 100% complete
load image[anim.gif]: 66 of 67, 100% complete
load image[anim.gif]: 67 of 68, 100% complete
load image[anim.gif]: 68 of 69, 100% complete
load image[anim.gif]: 69 of 70, 100% complete
load image[anim.gif]: 70 of 71, 100% complete
load image[anim.gif]: 71 of 72, 100% complete
load image[anim.gif]: 72 of 73, 100% complete
load image[anim.gif]: 73 of 74, 100% complete
load image[anim.gif]: 74 of 75, 100% complete
load image[anim.gif]: 75 of 76, 100% complete
load image[anim.gif]: 76 of 77, 100% complete
load image[anim.gif]: 77 of 78, 100% complete
load image[anim.gif]: 78 of 79, 100% complete
load image[anim.gif]: 79 of 80, 100% complete
load image[anim.gif]: 80 of 81, 100% complete
load image[anim.gif]: 81 of 82, 100% complete
load image[anim.gif]: 82 of 83, 100% complete
load image[anim.gif]: 83 of 84, 100% complete
load image[anim.gif]: 84 of 85, 100% complete
load image[anim.gif]: 85 of 86, 100% complete
load image[anim.gif]: 86 of 87, 100% complete
load image[anim.gif]: 87 of 88, 100% complete
load image[anim.gif]: 88 of 89, 100% complete
load image[anim.gif]: 89 of 90, 100% complete
load image[anim.gif]: 90 of 91, 100% complete
load image[anim.gif]: 91 of 92, 100% complete
load image[anim.gif]: 92 of 93, 100% complete
load image[anim.gif]: 93 of 94, 100% complete
load image[anim.gif]: 94 of 95, 100% complete
load image[anim.gif]: 95 of 96, 100% complete
load image[anim.gif]: 96 of 97, 100% complete
load image[anim.gif]: 97 of 98, 100% complete
load image[anim.gif]: 98 of 99, 100% complete
load image[anim.gif]: 99 of 100, 100% complete
load image[anim.gif]: 100 of 101, 100% complete
load image[anim.gif]: 101 of 102, 100% complete
load image[anim.gif]: 102 of 103, 100% complete
load image[anim.gif]: 103 of 104, 100% complete
load image[anim.gif]: 104 of 105, 100% complete
load image[anim.gif]: 105 of 106, 100% complete
mogrify image[anim.gif]: 106 of 107, 100% complete
classify image colors[output.gif]: 313 of 314, 100% complete
assign image colors[output.gif]: 313 of 314, 100% complete
classify image colors[output.gif]: 313 of 314, 100% complete
...
...
| |
doc_23534447
|
I'm using a similar table layout like the one linked for a project I'm currently doing but I can't seem to figure out how to not have the cells wrap onto a new row when the screen size shrinks. How is it done in this Pathfinding Visualizer project? What CSS property should I be applying to my table/tr/td? When I shrink my screen size, my table's cells wrap onto the next row making it so that every other row has a different number of columns. I'd like for the table width and, consequently, the table cells to just shrink in width and have the same columns in every row even for smaller screen sizes.
table {
border-collapse: collapse;
margin-left: 8px;
margin-right: 5px;
position: fixed;
bottom: 20px;
}
.grid-row {
white-space: nowrap;
}
.square {
background: #fff;
border: 1px solid #999;
padding: 0;
height: 25px;
width: 25px;
margin-right: -1px;
margin-top: -1px;
border: 1px solid rgb(175, 216, 248)
}
A: You haven't actually provided a link to your table or it's code.
But, if you're actually using a table structure, your white-space: nowrap; call should be applied to your td elements and not your tr elements.
Again, without a link to your table it's difficult to answer. But perhaps this will point you in the right direction?
| |
doc_23534448
|
Since MFC View/Document are not testable, I am going to make them as dumb as possible and to test the other classes with Boost Test framework. - Please let me know if you know better way or better test framework for this environment.
In order to make TDD work, I think having dependency injection is crucial for loosely coupled structure. How can I achieve this? Any reference or hint will be appreciated.
A: Use shared_ptr's to interfaces representing your classes.
I am thinking something like
#ifndef CLOCK_HPP_INCLUDED
#define CLOCK_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
class Clock
{
public:
static boost::shared_ptr<Clock> create();
virtual void init() = 0;
virtual double getSeconds() = 0;
virtual void sleepUntilNext(double howMuch) = 0;
protected: // No polymorphic deconstruction because of shared_ptr
~Clock()
{}
};
#endif
Then you could just take the clock implementation in your constructor, or have another method to set the implementation, like setClock or something.
Example of this would be
#include "clock.hpp"
class MyClass
{
public:
myClass(boost::shared_ptr<Clock> aClock) : myClock(aClock)
{
myClock.init();
}
private:
boost::shared_ptr<Clock> myClock;
}
Then in your unit testing you could do something like this:
boost::shared_ptr<Clock> mock = createMockClock();
MyClass b(mock);
mock.assertThatInitIsCalled();
You can also just ignore resources. The shared_ptr's will delete themselves.
The cost to this would be a little performance loss due to dynamic allocation, virtual function calls, and the overhead of shared_ptr.
The benefits would be increased modularity, lowered compile time, easier use of mocking frameworks like googlemock(they require interfaces anyways), and easier resource management(you will never have a null pointer).
| |
doc_23534449
|
Obviously I'm doing something wrong, and I'm unsure what search word I could use to find the solution (as I believe this question is answered several times already).
SELECT @id := actor_id FROM sakila.actor WHERE first_name = 'Ed' and last_name = 'Chase';
SELECT @film :=film_id FROM sakila.film_actor WHERE actor_id = @id;
SELECT title FROM sakila.film WHERE film_id = @film;
A: you need to do something like:
select title from sakila.film f
join sakila.film_actor fa on fa.film_id = f.film_id
where fa.actor_id = @id
this joins the last 2 queries into one, and is better than your way or using sub queries in my opinion
| |
doc_23534450
|
What must I change to ensure the widget appears in that launcher section?
| |
doc_23534451
|
So i have the next code :
int _tmain(int argc, _TCHAR* argv[])
{
std::wcin.get();//for console window input
int i=1;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// report settings
for (;i<argc;i++) printf("Argument %d:%s\n",i,argv[i]);
return 0;
}
for seeing how argc and argv works .
But no mater how many arguments i type in the console the argc won't increment.
It remains 1.
I know that argv[0] is the program name .My input is something like :"aaa bbb ccc ddd".
I belive for this argc should be 5 right ?
What am i doing wrong ? Why it will not increment ?
Thanks .
A: It seems like you're using MSVS (signature being _tmain(int argc, _TCHAR* argv[])). If you're running the code from the IDE, you'll need to specify the arguments in the project settings, not the command line.
Running from the command line like:
test.exe arg1 arg2
will also work correctly. What you're doing doesn't modify the arguments.
A: Calling wcin.get() does not affect argv or argc. The arguments are specified at the very beginning when the program is launched. They are specified on the command line, right after the program name, separated by spaces.
| |
doc_23534452
|
error:
Error:(27, 13) Failed to resolve: com.github.jiahuanyu:PopSeekbar:0.2.3
<a href="openFile">Show in File</a><br><a href="open.dependency.in.project.structure">Show in Project Structure dialog</a>
i am struck with this, please help me...
My build.gradle content.
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.example.admin.shopunter_user"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.android.gms:play-services:6.5.87'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'org.immutables:gson:2.1.0.alpha'
compile 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:0.5.2'
compile 'com.google.maps.android:android-maps-utils:0.4+'
compile 'com.android.support:design:23.0.1'
compile 'com.github.jiahuanyu:PopSeekbar:0.2.3'
compile 'com.android.support:support-v4:23.0.1'
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.android.support:recyclerview-v7:+'
}
A: Just add this in your build.gradle
dependencies {
compile 'com.github.jiahuanyu:PopSeekbar:0.2.3'
}
Then
Build > Clean Project Then Build > Rebuild Project
Then Click Invalidate Caches/Restart Options And Do Gradle (Sync)
A: I add this to buildscript{} to solve the problem.
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
| |
doc_23534453
|
For instance, how does it compare to the quite dramatic improvements from not-accelerated to accelerated models?
I know this is kind of vague and probably depends on the specifics of a model, but I'd be happy with examplary numbers.
A: I don't know if you will really find speed improvement anecdotes that helpful, as your results are going to be highly dependent on your own implementation.
That said, the following reference on How Acceleration Modes Work might be useful to you.
As described in this link...
The Accelerator mode generates and links code into a
C-MEX S-function. Simulink uses this acceleration target code to
perform the simulation...
...the model methods are separate from the Simulink
software and are part of the Acceleration target code. A C-MEX
S-function API communicates with the Simulink software, and a MEX API
communicates with MATLAB. The target code executes in the same process
as MATLAB and Simulink.
The link goes on to describe Rapid Acceleration, as such:
The Rapid Accelerator mode creates a Rapid Accelerator standalone
executable from your model. This executable includes the solver and
model methods, but it resides outside of MATLAB and Simulink. It uses
External mode (see Host/Target Communication) to communicate with
Simulink.
(Note that the actual link has some nice diagrams that help to illustrate this architecture).
I think that there are a few important things to takeaway from these descriptions. First, in Accelerator Mode, code is only generated for the model methods; however, in Rapid Accelerator Mode, code is also generated for the solver. In either case there will be some overhead due to communication between the generated code and Simulink (though in general that overhead would be greater in non-rapid accelerator mode).
Now, whether you are going to see significant differences between these acceleration modes and full-on code generation will most likely depend on how you would be using the generated code. You had stated that your application is intended to essentially analyze/visualize the outputs of simulink models. Do you intend for you application, itself, to be a Simulink model? If so, I imagine your workflow would be that you generate code for the "plug-in" model and then incorporate this into your "parent" model as an s-function. Based on the descriptions given above, my gut feeling is that you would not see much of a performance improvement compared to accelerator mode.
However, if your application is to be implemented outside of Simulink, then code generation would definitely be the way to go. In this case, you've completely eliminated the overhead of communicating with Simulink. In this workflow, you could, for example, generate a stand-alone executable from the "plug-in" model, execute that model to get the outputs, and then simply load those outputs for analysis and visualization into your application. Your application could be written in any language you want. In fact, you could even still write your application in MATLAB -- the key point, though, being that your application runs once the stand-alone executable (generated from the "plug-in" model) has finished executing, rather than interfacing with the plug-in model while it is executing.
| |
doc_23534454
|
I have so far come up with:
(?!.*xeditor.).*css?$
I tested in https://www.regextester.com/ but it still matches on strings like this:
globalsite/xeditor/styles.css
It shows that everything after globalsite/x i.e. editor/styles.css is a match. Because it contains xeditor in the string I want none of it to match.
How could I do this?
A: To match a string that ends in a specific pattern but does not contain another, you may use a regex like
^(?!.*pattern1).*pattern2$
The negative lookahead pattern must be anchored the lookahead check at the start, otherwise, the expression is checked at each position in the string, the (?!.*pattern1) may match a location that is not at the start, somewhere in the middle, and has no pattern1 to the right, while it can still be on the left.
Read more about why "Lookarounds (Usually) Want to be Anchored" at rexegg.com.
Here, you may use
^(?!.*xeditor).*\.css$
See the regex demo.
Note the . must be escaped to be parsed as a literal dot character.
Details
*
*^ - start of a string
*(?!.*xeditor) - a negative lookahead that fails the match if there are 0+ chars other than line break chars, as many as possible and then xeditor
*.* - 0+ chars other than line break chars, as many as possible
*\.css$ - .css substring at the end of the string.
| |
doc_23534455
|
For example, the point-based constraint between an item leading to superview.leading is 20.
Since in iPhone Xs Max, the total width is 414 points.
In the constraint section, should I define these values:
X.leading
equal
superview.leading
constant: 0
Priority: 1000
Multiplier: 20/414 = 0.0483
Is it the right way to do that?
A: Don't use it. percentage-base constraints in Xcode is not intuitive at all.
as for iPhone Xs Max , use safe area.
For apps with custom layouts, supporting iPhone X should also be
relatively easy, especially if your app uses Auto Layout and adheres
to safe area and margin layout guides.
Read more: https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/
| |
doc_23534456
|
LazyHighCharts provides functionality for Turbolinks5 and wraps chart building javascript with
(function() {
document.addEventListener("turbolinks:load", function() {
//code
window.chart_my = new Highcharts.Chart(options);
});
})()
But when I'm navigating away from page where graph was loaded previously with turbolink, I got error on newly loaded page.
Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
Looks like that all previous javascript which was loaded with "turbolinks:load" are reevaluating and causing highchart to throw error, because in new DOM there's no element to which that highchart graph is renderedTo.
I tried to unbind "turbolinks:load" event from document, but it doesn't work. It reevaluates it anyway.
Thought about solution to fork LazyHighCharts, to rewrite layout_helper, so javascript is outputed after dom element, but this would slow the page so the page flow would be
loaded-dom (graph)
evaluate js (sync)
-->
loaded-dom (graph)
evaluate js (sync)
--->
loaded-dom (graph)
evaluate js (sync)
etc. and it would slow down page load i Guess.
Maybe guys here have some solution to this problem.
A: Made a pull request to lazy_high_charts
document.addEventListener("turbolinks:load", function(e) {
// code
e.target.removeEventListener(e.type, arguments.callee);
});
| |
doc_23534457
|
class Name {
String firstName
String lastName
static belongsTo = [person: Person]
}
class Person {
Name name
String comment
}
and service with two methods:
class PersonService {
Person newPerson() {
def person = new Person()
person.name = new Name()
person
}
Person savePerson(Person person) {
person.save()
}
}
Now if I create a new Person with PersonService.newPerson() and then try to save it using savePerson() method using grails 1.3.7 everything works fine. With grails 1.4.0 or 2.0.0.M2 exception is thrown
Column 'name_id' cannot be null
Is this a bug in new grails? Or maybe there is something wrong with my code?
Test method:
void testPersonSave() {
def person = personService.newPerson()
person.name.firstName = 'f'
person.name.lastName = 'l'
person.comment = 'comment'
personService.savePerson(person) //throws an exception
}
A: Looks like a bug. Please JIRA: http://jira.grails.org/ .
| |
doc_23534458
|
The following code line would be in Form1:
public partial class form : Form
{
public static List<daftarBarang> tambahBarang = new List<daftarBarang>();
}
//UserControl
parent.tambahBarang.Add(new daftarBarang(nama, harga, stok, parent.tambahBarang.Count));
The issue is I cannot use my list, if I don't use static then the list won't save the results.
A: I don't understand exactly how you wired up your Form and UserControl but here's an example of a UserControl that works as a container which displays the items that you add via AddItem.
If this example does not help you to solve your problem please provide us with more information so that we can assist you further.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public class DaftarBarang
{
public string Nama { get; set; }
public int Harga { get; set; }
}
public class TheUserControl : UserControl
{
private readonly BindingList<DaftarBarang> list = new BindingList<DaftarBarang>();
public TheUserControl()
{
var grid = new DataGridView
{
DataSource = new BindingSource(list, null)
};
AutoSize = true;
Controls.Add(grid);
}
public void AddItem(DaftarBarang barang)
{
list.Add(barang);
}
}
public class TheForm : Form
{
public TheForm()
{
var uc = new TheUserControl();
uc.AddItem(new DaftarBarang { Nama = "Sepatu olahraga", Harga = 255000 });
uc.AddItem(new DaftarBarang { Nama = "Baju cantik", Harga = 85000 });
Controls.Add(uc);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.Run(new TheForm());
}
}
}
| |
doc_23534459
|
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
mean, lower, upper = [],[],[]
ci = 0.2
for i in range (20):
a = np.random.rand(100) # this is the output
MEAN = np.mean(a)
mean.append(MEAN)
std = np.std(a)
Upper = MEAN+ci*std
Lower = MEAN-ci*std
lower.append(Lower)
upper.append(Upper)
plt.figure(figsize=(20,8))
plt.plot(mean,'-b', label='mean')
plt.plot(upper,'-r', label='upper')
plt.plot(lower,'-g', label='lower')
plt.xlabel("Value", fontsize = 30)
plt.ylabel("Loss", fontsize = 30)
plt.xticks(fontsize= 30)
plt.yticks(fontsize= 30)
plt.legend(loc=4, prop={'size': 30})
In the above example, I drew %80 confidence interval. I have two questions:
1- Could you please tell me that this way of calculating and plotting the confidence interval is true?
2- I want to color the shadow area of the confidence interval. I have attached a figure, I want some thing like that. Could you please tell me if you have any solution? Thanks for your help.
A: I'm not qualified to answer question 1, however the answers to this SO question produce different results from your code.
As for question 2, you can use matplotlib fill_between to fill the area between two curves (the upper and lower of your example).
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
# https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
mean, lower, upper = [],[],[]
ci = 0.8
for i in range (20):
a = np.random.rand(100) # this is the output
m, ml, mu = mean_confidence_interval(a, ci)
mean.append(m)
lower.append(ml)
upper.append(mu)
plt.figure()
plt.plot(mean,'-b', label='mean')
plt.plot(upper,'-r', label='upper')
plt.plot(lower,'-g', label='lower')
# fill the area with black color, opacity 0.15
plt.fill_between(list(range(len(mean))), upper, lower, color="k", alpha=0.15)
plt.xlabel("Value")
plt.ylabel("Loss")
plt.legend()
| |
doc_23534460
|
I have a string with several <br /> in it. Replacing the first one with \r seems to work fine. I just can't figure out the syntax for global replaced. Tried several combinations, does not seem to work. Any help would be greatly appreciated.
A: If you check the console you'll see it errors as the REGEX pattern is invalid. You need to escape the forward slash.
/<br ?\/>/g
The ? also means the space is optional, so it will match <br/> as well as <br />.
A: try
notes.replace(/<br\/>/g,"\r")
A: With this you should be able to find any valid br Tag: As already said by Utkanos the ? means that the preceding character is optional in the search pattern. \s* means that any amount of spaces are matched.
notes.replace(/<br\s*\/?>/g,"\r");
| |
doc_23534461
|
Example:
In FosUserBundle, I don't need some of the columns (e.g. salt, expiresAt...) within my User class. How can I tell symfony/doctrine to not map this column anymore to the database / remove it from the mapping? I know how to "reconfigure" the columns by using @AttributeOverride, but how can I completly remove a field from the mapping?
Regards.
A: Pretty much all default properties of the FOSUB User entity are mandatory to make the bundle working as expected.
The fields you given (salt, expiresAt) are related to the security, as the most part of the User properties.
Remove one of them may have side effects in your user management.
Also, you can't Selectively inherit parts of an entity.
| |
doc_23534462
|
I want to send result js to mail, so my code is :
In my page index.php :
<form action="send.php" method="post" name="action" id="action">
<p>
<label>info1 :</label>
<input type="text" name="info1" id="info1" value="">
</p>
<p>
<label>info2 :</label>
<input type="text" name="info2" id="info2" value="">
</p>
<button type="button" class="btn" onclick="javascript:calculate()">Calcul javascript</button>
<p>info3 : <span id="info3"></span></p>
<p>info4 : <span id="info4"></span></p>
<p>info5 : <span id="info5"></span></p>
<button type="button" class="btn" onclick="javascript:result()">Result</button>
<input type="text" name="Name">
<input type="text" name="Email">
<input type="text" name="phone">
<input type="submit" value="Send">
ok, so i want send the result id (info3,info4 and info4) to my file php to send mail.
How i can do that please?
A: <button type="button" class="btn" id="result">Send</button>
// instead of submit input use a button <button type="button" class="btn" id="result">Send</button>
// if you want input value then simply write var q = $(#info1).val();
$(function() {
$("body").on("click", "#result", function() {
var q = $(#info1).val();
var p = $(#info2).val();
var t = $(#info3).text();
var m = $(#info4).text();
var v = $(#info5).text();
var n = "info3=" + t + "&info4=" + m + "&info5=" + v + "&info1=" + q + "&info2=" + p;
$.ajax({
type: "POST",
url: "ajax/mail.php",
data: n,
success: function(t) {
alert('Mail Sent');
}
});
});
});
A:
Load data asynchronously from the server using GET or POST HTTP
requests. Set data type (xml, json, script, text, html) and decode
returned data.
Sending POST requests is quite similar ($.post() in jQuery). However, there are lots of options available - more than can be covered in one post. Here's a useful helper function to get you started:
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
// example request with data object
var info3 = document.getElementById('info3').innerHTML;
var info4 = document.getElementById('info4').innerHTML;
var info5 = document.getElementById('info5').innerHTML;
postAjax('http://foo.bar/', {'info3' : info3, 'info4' :info4,'info5':info5 }, function(data){ console.log(data); });
| |
doc_23534463
|
(TextFields move upwards with keyboard. Botton stacked above the column is causing the issue)
Image before opening keyboard
Image after opening keyboard
I tried wrap column in a Padding widget and gave a bottom padding but still the same result. Please suggest a way to position textfields above the button.
Note: First time poster. Please forgive if there is any mistakes. Thank You
return SafeArea(
child: Stack(
fit: StackFit.expand,
children: [
SingleChildScrollView(
child: Container(
child: Column(
children: [
Container(
color: Colors.deepOrange,
width: double.maxFinite,
height: height * 0.3,
),
Container(
color: Colors.black,
width: double.maxFinite,
height: height * 0.56,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Utils().colSpacer20,
TextBox(hint: "name", editingController: _controller),
Utils().colSpacer20,
TextBox(hint: "name", editingController: _controller),
Utils().colSpacer20,
TextBox(hint: "name", editingController: _controller),
Utils().colSpacer20,
TextBox(hint: "name", editingController: _controller),
Utils().colSpacer20,
TextBox(hint: "name", editingController: _controller)
],
),
),
),
],
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: FlatButton(
color: Colors.blue[900],
onPressed: () {},
child: Text(
"Save",
style: TextStyles().subTextStyleWhite,
),
minWidth: double.maxFinite,
height: height * 0.1,
),
)
],
),
);
Edit: scrollPadding property of TextField widget solved the issue.
Thanks @Anitesh Reddy.
A: Keep padding/margin or sizedBox( height:height*0.12 ) at the bottom of the column so that the widget in positioned will move down and leave space.
use scrollpadding property
| |
doc_23534464
|
.circle {
height: 130px;
width: 130px;
background: none;
position: absolute;
border-radius: 100px;
border-right: 3px solid blue;
left: 140px;
top: 134px;
transform: rotate(-45deg)
}
.letter {
height: 100px;
width: 100px;
position: absolute;
color: gray;
left: 95px;
top: 120px;
font-size: 200px;
transform: rotate(-45deg);
}
<div class="letter">D</div>
<div class="circle"></div>
| |
doc_23534465
|
https://www.aliexpress.com/af/category/200010058.html?categoryBrowse=y&origin=n&CatId=200010058&spm=a2g0o.home.108.18.650c2145CobYJm&catName=backpacks
I used selenium as a middleware to render javascript and this is the code for that :
def process_request(self, request, spider):
self.driver.get(request.url)
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.CLASS_NAME, '_3t7zg'))
)
# self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(10)
links = self.driver.find_elements("xpath", '//div[1]/div/div[2]/div[2]/div/div[2]/a[@href]')
The problem is that on the webpage there are 60 products, when I look at the number of products I have scraped I find 11. I don't know what the problem is.
| |
doc_23534466
|
private String signMessage(String message) throws Exception {
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(getPrivate(privateKeyPath));
rsa.update(message.getBytes());
return rsa.sign().toString();
}
public PrivateKey getPrivate(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
To clarify the privatekeyPath I am supplying is similar to /path/test.der.
However, I am getting the following error when trying to sign the message - java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
What is wrong here? Why cant I seem to sign a message with the private key? Can someone specify a working way to get this done?
A: It seems that your getPrivate method is correct, so I think the problem is in the generation of the key or in the format
A der file can contain certificates or private keys in binary. In the case of pem files they are encoded in base 64. Usually you need a .key file or a .pem file whose content starts with -----BEGIN PRIVATE KEY-----
Make sure you're using a binary der format containing a pkcs#8 key so Java can read it. See a full example here: https://stackoverflow.com/a/19387517/6371459
In your code rsa.sign().toString() is an error because a binary array can not be converted to a string. You should use the binary data or encode it to base 64
Note that in the linked question the signature is encoded in base64. You do not need to do this because you can use the binary array.
| |
doc_23534467
|
I am using Visual Studio 2013 and ASP.NET MVC5. My Facebook login method is working fine. But when I retrieve email from Facebook, it is giving me null exception. My externalLoginCallback method is below:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
if (result == null || result.Identity == null)
{
return RedirectToAction("Login");
}
var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
if (idClaim == null)
{
return RedirectToAction("Login");
}
var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");
//retrieving email from facebook here
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;//this line is throwing null exception
.
.
.
}
I commented where error throw in my code.
This is how I configured Facebook in Startup.Auth.cs
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "x",
AppSecret = "y"
};
facebookAuthenticationOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookAuthenticationOptions);
I also tried like this:
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "x",
AppSecret = "y",
Scope = { "email" },
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
return Task.FromResult(true);
}
}
});
Both are not working. What is wrong with my code and how can I fix it?
A: You can try this:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "xxxxxxx",
AppSecret = "xxxxxx",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location"
};
and then define this class:
public class FacebookBackChannelHandler : HttpClientHandler
{
protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
{
request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
}
var response = await base.SendAsync(request, cancellationToken);
return response;
}
}
finally, you can get email (and first_name,last_name,location) by doing the following in "ExternalLoginCallback" method in account controller:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("LoginRegister");
}
// GET MAIL AND NAME
var email = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
var name= loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
| |
doc_23534468
|
PO Material. Material Desc.Amount_USD PO_Pur_Org Count Total
0 6001488.0 SCRAP: Light (L/S) 485.33300 SA02 4624 2.244180e+06
1 6001488.0 SCRAP: Light (L/S) 728.00000 SA02 1888 1.374464e+06
2 6001488.0 SCRAP: Light (L/S) 242.66700 SA02 1778 4.314619e+05
3 6001488.0 SCRAP: Light (L/S) 606.66700 SA02 1044 6.333603e+05
A: If I understand you correctly, then you will want to use groupby to find the like values in PO Material, then sum the Amount_USD.
Try this:
df.groupby('PO Material')['Amount_USD'].sum()
| |
doc_23534469
|
I have tried this library but it breaks fab position according to bottom appbar after menu close.
Here what I got as a result
The code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
app:layout_scrollFlags="scroll|enterAlways|snap"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabAlignmentMode="end"
app:backgroundTint="?colorPrimary"
android:layout_gravity="bottom">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
app:useCompatPadding="true"
app:layout_anchor="@id/bottomBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fab"/>
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#53000000"
android:visibility="invisible"
android:id="@+id/overlay"/>
<io.codetail.widget.RevealFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<io.files.view.MenuCardView
android:id="@+id/menu"
android:visibility="invisible"
android:layout_margin="56dp"
android:layout_gravity="bottom|end"
android:layout_width="wrap_content"
app:cardUseCompatPadding="true"
app:menu="@menu/new_tab_options"
android:layout_height="wrap_content"/>
</io.codetail.widget.RevealFrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
MainActivity.kt
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.konifar.fab_transformation.FabTransformation
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
overlay.setOnClickListener {
FabTransformation.with(fab)
.setOverlay(it)
.transformFrom(menu)
}
fab.setOnClickListener {
FabTransformation.with(it)
.setOverlay(overlay)
.transformTo(menu)
}
}
override fun onBackPressed() {
if(menu.visibility== View.VISIBLE){
FabTransformation.with(fab)
.setOverlay(overlay)
.transformFrom(menu)
}else super.onBackPressed()
}
}
A: Just found a solution:
Use com.google.android.material.transformation.FabTransformationSheetBehavior for sheet layout and com.google.android.material.transformation.FabTransformationScrimBehavior for overlay view. To support nice animation use com.google.android.material.transformation.TransformationChildCard or com.google.android.material.transformation.TransformationChildLayout for root view of the sheet. To transform fab into sheet set isExpanded to fab to true and to transform it backwards set isExpanded to false
| |
doc_23534470
|
my_list = [[['b', ['a'], 'c'], ['d', ['a', 'b'], 'e']],
[['j', ['a', 'f']], ['q', 't']]]
ref_list = [[['q', 'w', 't'], ['y', 'u']],
[['s', 'o'], ['p', 'k', 'l']]]
newlist = []
for num, i in enumerate(my_list):
small_list = []
for num_1, j in enumerate(i):
semilist = []
for k in j:
if isinstance(k, list):
onelist = []
for a in k:
for ii in ref_list[num][num_1]:
onelist.append(ii)
semilist.append(onelist)
else:
semilist.append(k)
small_list.append(semilist)
newlist.append(small_list)
print(newlist)
The output I am getting is -
[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u', 'y', 'u'], 'e']], [['j', ['s', 'o', 's', 'o']], ['q', 't']]]
The output I am looking for is of sort -
[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u'], 'e']], [['j', ['s', 'o']], ['p', 'k', 'l']]]
I want to replace elements of innermost list of "my_list" with the elements of the "ref_list".
A: Try:
ref_list_flat = [l for sublist in ref_list for l in sublist]
for i, l1 in enumerate(my_list):
for j, l2 in enumerate(l1):
#check if this is the innermost list
if not any(isinstance(l3, list) for l3 in l2):
my_list[i][j] = ref_list_flat.pop(0)
else:
for k, l3 in enumerate(l2):
if isinstance(l3, list):
my_list[i][j][k] = ref_list_flat.pop(0)
>>> my_list
[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u'], 'e']],
[['j', ['s', 'o']], ['p', 'k', 'l']]]
A: Try:
my_list = [
[["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
[["j", ["a", "f"]], ["q", "t"]],
]
ref_list = [[["q", "w", "t"], ["y", "u"]], [["s", "o"], ["p", "k", "l"]]]
for a, b in zip(my_list, ref_list):
for i, subl in enumerate(a):
for ii, v in enumerate(subl):
if isinstance(v, list):
subl[ii] = b[i]
break
else:
a[i] = b[i]
print(my_list)
Prints:
[
[["b", ["q", "w", "t"], "c"], ["d", ["y", "u"], "e"]],
[["j", ["s", "o"]], ["p", "k", "l"]],
]
EDIT: To append elements from 2nd list instead replacing:
my_list = [
[["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
[["j", ["a", "f"]], ["q", "t"]],
]
ref_list = [[["q", "w", "t"], ["y", "u"]], [["s", "o"], ["p", "k", "l"]]]
for a, b in zip(my_list, ref_list):
for i, subl in enumerate(a):
for ii, v in enumerate(subl):
if isinstance(v, list):
subl[ii].extend(b[i])
break
else:
a[i].extend(b[i])
print(my_list)
Prints:
[
[["b", ["a", "q", "w", "t"], "c"], ["d", ["a", "b", "y", "u"], "e"]],
[["j", ["a", "f", "s", "o"]], ["q", "t", "p", "k", "l"]],
]
EDIT2: To add elements of 2nd list at the beginning of first list:
my_list = [
[["b", ["a"], "c"], ["d", ["a", "b"], "e"]],
[["j", ["a", "f"]], ["q", "t"]],
]
ref_list = [[["q", "w", "t"], ["y", "u"]], [["s", "o"], ["p", "k", "l"]]]
for a, b in zip(my_list, ref_list):
for i, subl in enumerate(a):
for ii, v in enumerate(subl):
if isinstance(v, list):
subl[ii] = b[i] + subl[ii]
break
else:
a[i] = b[i] + a[i]
print(my_list)
Prints:
[
[["b", ["q", "w", "t", "a"], "c"], ["d", ["y", "u", "a", "b"], "e"]],
[["j", ["s", "o", "a", "f"]], ["p", "k", "l", "q", "t"]],
]
| |
doc_23534471
|
describe("Counter", () => {
it("initially displays 0", () => {
render(<Counter />);
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
it("displays the given initial value", () => {
render(<Counter initialValue={10} />);
expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
});
it("has a button for incrementing the value", () => {
render(<Counter />);
userEvent.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
});
describe("when the maxValue is given", () => {
it("does not allow to increment the value above the given maximum", () => {
render(<Counter initialValue={9} maxValue={10} />);
userEvent.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "+1" })).toBeDisabled();
});
});
it("has a button for decrementing the value", () => {
render(<Counter initialValue={2} />);
userEvent.click(screen.getByRole("button", { name: "-1" }));
expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
});
it("does not allow to decrement the value below zero", () => {
render(<Counter initialValue={0} />);
expect(screen.getByRole("button", { name: "-1" })).toBeDisabled();
userEvent.click(screen.getByRole("button", { name: "-1" }));
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
it("has a button for resetting the value", () => {
render(<Counter initialValue={2} />);
userEvent.click(screen.getByRole("button", { name: "reset" }));
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
});
Is it a good practice to dry-up it with some handy helpers, like:
describe("<Counter /> component", () => {
const getIncrementButton = () => screen.getByRole("button", { name: "+1" });
const getDecrementButton = () => screen.getByRole("button", { name: "-1" });
it("has a button for incrementing the value", () => {
render(<Counter />);
userEvent.click(getIncrementButton());
expect(getValue()).toHaveTextContent("Counter value is 1");
});
});
I did some research and I couldn't find any decent resources about such approach.
| |
doc_23534472
|
A: It doesn't use same wording but on 7. November, 2019 PEP602 was accepted which introduced release cycles. You can find more info about current versions and their states here.
A: not currently
see PEP407 status: "deferred"
https://www.python.org/dev/peps/pep-0407/
| |
doc_23534473
|
So now should i generate an other APK and publish it on google play console or is there any other method to show ads on my app it's already on google play store (without ads)
A: Short answer - no, you can't.
You must need an advertising-id set for your ads (which is unique to every ad). You must need to publish an update to your app with new ads.
You won't lose any of your existing users if you release the update, they will just receive an updated app from google play.
| |
doc_23534474
|
I put the system.net configuration into app.config:
<system.net>
<mailSettings>
<smtp from="mail@domain.com">
<network host="myserver.com" port="25" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
And I instantiate the SmtpClient without params:
SmtpClient client = new SmtpClient();
But the configuration is not read (I'm trying to test the library with NUnit) and I get a System.InvalidOperationException, because the configuration is not read and thus the host is null.
Shouldn't the configuration be read automatically?
A: Make sure you add your configuration block (as shown above) to the {appName}.exe.config or web.config - the configuration for the class library is taken from one of those files at runtime, not from the app.config of the class library.
A: I've just realized I'm definitely doing it the wrong way (there's also a similar post from John about it and the solution is there...).
The mailsettings is available only at the application level, so the test project should know about your settings to take them into account.
Thanks to John and Davide for pointing me to the right direction!
| |
doc_23534475
|
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
I wonder if the transaction is aborting due to the IntegrityError (which I am intentionally ignoring.) I am trying to replace the functionality of initial_data fixtures that are apparently deprecated in apps that use 1.7's new migrations.
my migrations file:
from django.db import models, migrations, IntegrityError
TAGS = ['Foo', 'Bar', 'Baz', ...]
def populate_initial_tags(apps, schema_editor):
Tag = apps.get_model('widgets', 'Tag')
for text in TAGS:
try:
Tag.objects.create(text=text)
except IntegrityError:
pass
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(populate_initial_tags)
]
my models
class Tag(models.Model):
text = models.CharField(max_length=128)
slug = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.text
@receiver(pre_save, sender=Tag, dispatch_uid='update_tag_slug')
def update_tag_slug(sender, instance, **kwargs):
instance.slug = slugify(instance.text)
A: Your guess is correct, you can't simply ignore IntegrityErrors if you're inside a transaction (as migrations are). Instead do this:
for text in TAGS:
try:
with transaction.atomic():
Tag.objects.create(text=text)
except IntegrityError:
pass
See the documentation here.
| |
doc_23534476
|
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
A: Yes, you can let the browser validate it partially.
To do this, you can use the pattern attribute, required, etc.
Further Reading.
A: For built in email validation set up input type to email:
<input type="email" name="email">
If it's required add another attribute:
<input type="email" name="email" required>
But remember, that it's only client side validation and supported by not all browsers, so you must check input on server as well
| |
doc_23534477
|
I have tried:
api --method GET /repos/my_name/my_project/pulls -H "Accept: application/vnd.github+json" -f q="Bump in:title"
and
api --method GET '/repos/my_name/my_project/pulls?q=Bump in:title' -H "Accept: application/vnd.github+json"
however the filtering does not apply
A: I needed to use the search api instead:
gh api '/search/issues?q=is:pr+repo:my_name/my_project+Bump+in:title
| |
doc_23534478
|
{"4":"25","8":"15"}
please help.
A: Node.js server uses async model in one single thread, which means at any time, only one request (connId) is under execution by Node (except... you have multiple node.js instance, but let's keep the scenario simple and ignore this case).
When one request is processed (running its handler code), it may start an async task such as read a file, and continue execution. The request itself's handler code would be executed without waiting for async task, and when this handler code is finished running, from Node.js point of view, the request handling itself is done -- the handling of async task's result is another thing in another time, node does not care about the progress of it.
Thus, in order to return remaining time of all requests -- I guess this is the remaining time of other request's async task, because remaining time of other request's handler code execution does not make any sense, there must be some place to store the information of all requests, including:
*
*request's connId and startTime (the time when request is received).
*request's timeout value, which is passed as parameter in URL.
*request's estimated remaining time, this information is mission specific and must be retrieved from other async task related services (you can pull time by time using setInterval or make other services push the latest remaining time). Node.js doesn't know the remaining time information of any async task.
In this way, you can track all running requests and their remaining time. Before one request is returned, you can check the above "some place" to calculate all requests' remaining time. This "some place" could be global variable, memory database such as Redis, or even a plain database such as MySQL.
Please note: the calculated remaining time would not be accurate, as the read&calculation itself would cost time and introduce error.
| |
doc_23534479
|
The ID seems to be valid per description, and NFTs are there. I'm using the tool on the page (https://xrpl.org/websocket-api-tool.html#ledger_entry-by-object-id) to complete queries using ledger method.
Are there any actual code/samples for NFTokenPage entries other than the format doc? Any help would be appreciated.
Using the testnet, I can see NFTs in accounts using the same tool via account methods.
| |
doc_23534480
|
So I pulled, and usually when I do this, I would get a list of the files that had changes and need to resolve them, add them, and then push.
However something different happened today when encountering this. I got this message:
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint: git config pull.rebase false # merge
hint: git config pull.rebase true # rebase
hint: git config pull.ff only # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.
Whenever setting up a new machine, I've never seen this before. I'm using the same .gitconfig on two other machines where I haven't seen this message:
[user]
name = my name
email = my email
[format]
numbered = auto
[color]
branch = yes
diff = auto
pager = yes
status = auto
I've done this many times and I suddenly have amnesia. I do not recall this hint/error from Git ever (6 years). Is this new? Maybe I can look at history of Git's source? If not, what's the default?
A: It is indeed new (partly introduced in Git 2.27, with a fix in 2.29): you can and should now configure pull.rebase and pull.ff to some setting(s).
The previous default default was the equivalent of pull.rebase false and pull.ff true. This makes git pull run git merge, doing a fast-forward non-merge "fake" merge if possible, or a real merge if not possible.
Configuring pull.ff to only makes git pull run the equivalent of git merge --ff-only as its second command (provided you're not rebasing). This is my general personal preference, but I don't have Git 2.29 or later everywhere, so I still use my own run git fetch, then poke around, then decide and maybe use my git mff alias to do a fast-forward-only merge process.
A: Short explanation of your issue:
Git force us to choose how it should handle out of sync between our remote branch (e.g. origin/develop) and local branch (develop), so it made it easy to modify the behavior and added this message to remind you that you might want to change the default.
To fix it we need to change the default running the following:
git pull --ff-only
or event better as a global default with
git config --global pull.ff only
A: If it helps someone may follow this alternative way
I had to face on this issue. But below suggestion not worked for me
- git config pull.rebase false
- git config pull.rebase true
- git config pull.ff only
OR even adding 'git config --global pull.ff only' not worked
Finally I have solved this issue in another way.
steps :
- Create a new branch // git create branch new_branch
- switch to new branch // git checkout new_branch
- merge prev_branch to new_branch // git merge origin prev_branch
| |
doc_23534481
|
It's possible to access the force attribute of a UITouch instance. Is there some other way?
A: Look in UITouch
// Force of the touch, where 1.0 represents the force of an average touch
@available(iOS 9.0, *)
public var force: CGFloat { get }
// Maximum possible force with this input mechanism
@available(iOS 9.0, *)
public var maximumPossibleForce: CGFloat { get }
| |
doc_23534482
|
So I use preventDefault() to stop keyEvent.
And it works fine at otherBrowser (iOS, Chrome, Android2.3).
But it doesn't work in Android 3.0 (Honeycomb)
This is my test sample.
<html>
<head>
<title></title>
<script type="text/javascript">
function start( e ) {
var input1 = document.getElementById("input1");
input1.addEventListener("keydown",keydown,false);
input1.addEventListener("keypress",keypress,false);
input1.addEventListener("keyup",keyup,false);
}
function keydown( e ) {
e.preventDefault();
e.returnValue = false;
return false;
}
function keypress( e ) {
e.preventDefault();
e.returnValue = false;
return false;
}
function keyup( e ) {
e.preventDefault();
e.returnValue = false;
return false;
}
window.onload= start;
</script>
</head>
<body>
<input id="input1"></input>
</body>
</html>
Is there something wrong in my testSample?
| |
doc_23534483
|
<a href="https://rads.stackoverflow.com/amzn/click/com/B008EYEYBA" rel="nofollow noreferrer"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&ASIN=B008EYEYBA&Format=_SL110_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=mytwitterpage-20" ></a><img src="http://www.assoc-amazon.com/e/ir?t=mytwitterpage-20&l=as2&o=1&a=B008EYEYBA" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
btw, below is the exact php variable that I want when the user put the script above in a text area.
$str = "<a href="https://rads.stackoverflow.com/amzn/click/com/B008EYEYBA" rel="nofollow noreferrer"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&ASIN=B008EYEYBA&Format=_SL110_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=mytwitterpage-20" ></a><img src="http://www.assoc-amazon.com/e/ir?t=mytwitterpage-20&l=as2&o=1&a=B008EYEYBA" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />";
any help is greatly appreciated. thanks
A: use like this
<?php
$str = '<a href="http://rads.stackoverflow.com/amzn/click/B008EYEYBA"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&ASIN=B008EYEYBA&Format=_SL110_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=mytwitterpage-20" ></a><img src="http://www.assoc-amazon.com/e/ir?t=mytwitterpage-20&l=as2&o=1&a=B008EYEYBA" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />' ;
echo htmlentities($str);
?>
A: If you need to output your value in HTML, you need to replace your < and > with < and >. Best is to use htmlspecialchars() function for that.
Also you were told correctly that your string has unescaped quotes in it (replace inside quotes with \").
| |
doc_23534484
|
I am on Ubuntu Linux 64-bit, running 64 bit R 3.0.2
setEPS()
postscript("Figure 1.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1,1)
legend("topleft", c("ΔValue"))
dev.off()
png("Figure 1.png")
plot(1,1)
legend("topleft", c("ΔValue"))
dev.off()
A: It works if you create the delta symbol with the expression function:
plot(1,1)
legend("topleft", expression(paste(Delta, "Value")))
| |
doc_23534485
|
I am using the Composer-free method that was posted here:
Get a localized name of the users city via Maxmind GeoLite2 Free
I'm sure its incredibly simple, but I can't figure out how to actually pass an IP address and have it return the country.
After the $reader = new Reader... line I have $place = $reader->country('##.###.##.###'); (where the #'s are actual IP address numbers) and it's not working. I tried replacing 'country' with 'city' and that didn't work either. I'm sure its something simple, I'm just not sure what parameters I need to be using to get the country returned.
The error that is shown in the error log is 'PHP Fatal error: Call to undefined method MaxMind\Db\Reader::city() in <<< path to benchmark.php >>>)'
Any ideas/suggestions would be greatly appreciated.
A: There's no city() or country() functions defined in the files you're including (based on the answer you linked to.) Instead you're supposed to use get() to get the IP geographic information, like so:
require_once __DIR__ . '/' . 'Db/Reader.php';
require_once __DIR__ . '/' . 'Db/Reader/Decoder.php';
require_once __DIR__ . '/' . 'Db/Reader/InvalidDatabaseException.php';
require_once __DIR__ . '/' . 'Db/Reader/Metadata.php';
require_once __DIR__ . '/' . 'Db/Reader/Util.php'; // new 2014/09
use MaxMind\Db\Reader;
$mmdb= 'GeoLite2-Country.mmdb';
$reader = new Reader( __DIR__ . '/' . $mmdb );
$ipData = $reader->get('##.###.##.###');
echo $ipData['country']['names']['en'];
Where you replace ##.###.##.### with the IP you want to get info for. Obviously this requires you have all the required code files and GeoLite2-Country.mmdb
So the complete steps would be:
*
*Download the MaxMind-DB-Reader-php from https://github.com/maxmind/MaxMind-DB-Reader-php
*Copy the Db folder found in src/MaxMind to the directory with the file containing the above code.
*Download the GeoLite2 Country MaxMind DB from http://dev.maxmind.com/geoip/geoip2/geolite2/
*Unzip the downloaded gzip and copy the GeoLite2-Country.mmdb file to the same directory as the file containing the above code.
*You should now be able to run the above code! Just make sure you replace ##.###.##.### with a real IP.
A: This is a simple way. First you have to insert the user IP in MySQL. Then you have to run fetch query, something like this
//database connect or includ database php file
//user_ip detect
$geo = json_decode(file_get_contents("http://extreme-ip-lookup.com/json/$user_ip"));
$country = $geo->country;
$city = $geo->city;
$ipType = $geo->ipType;
$businessName = $geo->businessName;
$businessWebsite = $geo->businessWebsite;
echo "Location of $user_ip: $city, $country\n";
echo $ip_address;
| |
doc_23534486
|
Result:
_CurrentUserAccounts: [
[Current Account, 10.06, United States Dollar USD],
[Demand Deposit, 55.22, British Pound GBP],
[Current Account, 250, Euro EUR],
[Deposit Account, 0, Euro EUR]
]
Format:
[AccountName, CurrentBalance, CurrencyName],
I need to use this info (List>) to build a ListTile.
This is for only one user. Some user might 1 account and some of them might have over 10 accounts.
What is the best practice to show this data? I am planing to use ListTile so, if user tabs the ListTile so they can get details of the
certain account.
So, How to use FutureBuilder to build ListTile using List data?
A: You have to provide an instance of FutureBuilder to home or root widget. As you can see below.
body: new FutureBuilder<List<Country>>(
future: fetchCountry(new http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? new CountyList(country: snapshot.data)
: new Center(child: new CircularProgressIndicator());
},
I have found a simple example for it here.
| |
doc_23534487
|
ByteArrayOutputStream image1baos = new ByteArrayOutputStream();
image1 = resizeImage(cropImage(image1, rect1), 150);
ImageWriter writer = null;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
if (iter.hasNext()) {
writer = (ImageWriter) iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream(image1baos);
writer.setOutput(ios);
// set the compression quality
ImageWriteParam iwparam = new MyImageWriteParam();
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(0.2f);
// write image 1
writer.write(null, new IIOImage(image1, null, null), iwparam);
ios.flush();
// set image 1
c.getItem1().setImageData(image1baos.toByteArray());
I'd like to convert the alpha channel to white, not black as it does by default, but I couldn't find a way to do that. Will appreciate any help!
A: My solution is ugly and probably slow, but it's a solution :)
BufferedImage img = <your image>
for( int i = 0; i < img.getWidth( ); i++ )
for( int j = 0; j < img.getHeight( ); j++ ) {
// get argb from pixel
int coli = img.getRGB( i, j );
int a = coli >> 24 & 0xFF;
int r = coli >> 16 & 0xFF;
int g = coli >> 8 & 0xFF;
int b = coli & 0xFF;
coli &= ~0xFFFFFFFF;
// do what you want with a, r, g and b, in your case :
a = 0xFF;
// save argb
coli |= a << 24;
coli |= r << 16;
coli |= g << 8;
coli |= b << 0;
img.setRGB( i, j, coli );
}
}
Of course, you can reduce the code by 60% if you just need to adjust the alpha channel. I kept all RGB stuff for further referece.
| |
doc_23534488
|
It seemed to ignore everything and get products from anywhere regardless of country
SELECT *
FROM products
WHERE `country` = 'America' AND
product = 'Product 1' AND
product = 'Product 2' AND
completed = 'complete'
Statement Attempt 2:
The result of this was that is returned 0 results, even though the results are there hypothetically.
SELECT *
FROM products
WHERE `country` = 'America' AND
product = 'Product 1' OR
product = 'Product 2' AND
completed = 'complete'
A: Your first query is logically incorrect due to product = product 1 AND product = product 2, where clause filter rows one by one, so a single row at same time cannot contain both values in product column.
Your second query has an issue that you introduced and OR criteria so it ignores the country filter if there is product 2 with status completed in another country , to correct your query you need to group your OR criteria by using parenthesis (condition 1 or condition 2) and some other condition
SELECT *
FROM products
WHERE `country` = 'America'
AND (product = 'Product 1' OR product = 'Product 2')
AND completed = 'complete'
Or you could use IN clause to simplify your criteria
SELECT *
FROM products
WHERE `country` = 'America'
AND product IN('Product 1','Product 2')
AND completed = 'complete'
| |
doc_23534489
|
I tried subclassing an UILabel and to override drawRect but I had no success. Not only I didn't get any red corner I also lost the label.text that is showed if I do not override drawRect.
-(void) drawRect: (CGRect) rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx,0,0);
CGContextMoveToPoint(ctx,10,0);
CGContextMoveToPoint(ctx,0,10);
CGContextClosePath(ctx);
CGContextSetRGBFillColor(ctx,50,0,0,1);
CGContextFillPath(ctx);
}
Thanks!
Nicola
P.s. I wanted to add an image of the label I want to create but I need a reputation of at least 10 point to add it :(
A: As always, it would have been sufficient to read the documentation of the function you're using. You made assumptions instead, which turned out to be wrong (no surprise).
The CGContextMoveToPoint() function begins a new subpath without drawing. If you want to draw a line, then... well... use the function that draws a line:
CGPoint points[] = {
CGPointMake(0, 0),
CGPointMake(10, 0),
CGPointMake(0, 10),
CGPointMake(0, 0)
};
CGContextAddLines(ctx, points, sizeof(points) / sizeof(points[0]));
| |
doc_23534490
|
Value Map<Key, Value>::valueFor(const Key& key);
Unfortunately, the most used case is for Key = std::string where we usually call the method with string literals such as:
const Value v = map.valueFor("my_key");
We loose a few cycles creating the std::string. Therefore, I would like to add an overload
Value Map<std::string, Value>::valueFor(const char* key);
when Key = std::string. I am sure that the compiler can even compute the hash at compile time with such a signature which would also help to speedup things.
Is there a way to do that in C++11 without template specializing the whole Map class and rewrite all the methods?
A: You can just add another overload valueFor(char const * key). Probably you then also want to disable this overload with SFINAE if the Key is not std::string.
#include <iostream>
#include <string>
#include <type_traits>
template < typename Key, typename Value >
struct Map
{
Value valueFor(Key const& key)
{
std::cout << "valueFor(const Key& key)\n";
return Value{};
}
template < typename _Key = Key,
typename = typename std::enable_if< std::is_same < _Key, std::string >::value >::type >
Value valueFor(char const * key)
{
std::cout << "valueFor(char const * key)\n";
return Value{};
}
};
int main()
{
Map<std::string, int> map;
int v = map.valueFor("my_key");
Map<int, int> other_map;
//int v = other_map.valueFor("my_key"); // BOOM!
}
A: Just weaken your type requirements. Your valueFor doesn't (need to) care what type the argument is, so long as the expression hash<Key>(arg) is valid.
So, you can template valueFor on its argument type, and just specialise your hash function and if necessary your key comparator.
eg. (untested, and using C++17 string_view for brevity)
template <typename K>
struct Hasher
{
static size_t hash(K const &k) { return std::hash<K>()(k); }
};
template <>
struct Hasher<std::string>
{
static size_t hash(std::string const &s) {
return std::hash<std::string>()(s);
}
static size_t hash(std::string_view const &sv) {
return std::hash<std::string_view>()(sv);
}
static size_t hash(const char *cstr) {
return std::hash<std::string_view>()({cstr});
}
};
template <typename Key, typename Value>
template <typename KeyArg>
Value Map<Key,Value>::valueFor(KeyArg&& arg)
{
auto hash = Hasher<Key>::hash(std::forward<KeyArg>(arg));
// ...
}
| |
doc_23534491
|
Thanks in advance....
-(void)contrast:(float)value{
CGImageRef img=refImage.CGImage;
CFDataRef dataref=CopyImagePixels(img);
UInt8 *data=(UInt8 *)CFDataGetBytePtr(dataref);
int length=CFDataGetLength(dataref);
for(int index=0;index<length;index+=4){
int alphaCount = data[index+0];
int redCount = data[index+1];
int greenCount = data[index+2];
int blueCount = data[index+3];
alphaCount = ((alphaCount-128)*value ) + 128;
if (alphaCount < 0) alphaCount = 0; if (alphaCount>255) alphaCount =255;
data[index+0] = (Byte) alphaCount;
redCount = ((redCount-128)*value ) + 128;
if (redCount < 0) redCount = 0; if (redCount>255) redCount =255;
data[index+1] = (Byte) redCount;
greenCount = ((greenCount-128)*value ) + 128;
if (greenCount < 0) greenCount = 0; if (greenCount>255) greenCount =255;
data[index+2] = (Byte) greenCount;
blueCount = ((blueCount-128)*value ) + 128;
if (blueCount < 0) blueCount = 0; if (blueCount>255) blueCount =255;
data[index+3] = (Byte) blueCount;
}
size_t width=CGImageGetWidth(img);
size_t height=CGImageGetHeight(img);
size_t bitsPerComponent=CGImageGetBitsPerComponent(img);
size_t bitsPerPixel=CGImageGetBitsPerPixel(img);
size_t bytesPerRow=CGImageGetBytesPerRow(img);
CGColorSpaceRef colorspace=CGImageGetColorSpace(img);
CGBitmapInfo bitmapInfo=CGImageGetBitmapInfo(img);
CFDataRef newData=CFDataCreate(NULL,data,length);
CGDataProviderRef provider=CGDataProviderCreateWithCFData(newData);
CGImageRef newImg=CGImageCreate(width,height,bitsPerComponent,bitsPerPixel,bytesPerRow,colorspace,bitmapInfo,provider,NULL,true,kCGRenderingIntentDefault);
[ImgView setImage:[UIImage imageWithCGImage:newImg]];
CGImageRelease(newImg);
CGDataProviderRelease(provider);
}
A: You might have some memory leaks.
Any function that is CF...Create() will need to have corresponding CFRelease() called on it. The following has no release:
CFDataRef newData=CFDataCreate(NULL,data,length);
I think you need to clean up after copying as well:
CFDataRef dataref=CopyImagePixels(img);
You cleaned up after newImg okay. Can't see any other leaks but check your Create/Copying that you clean up the memory afterwards.
| |
doc_23534492
|
def loop_for(df):
gpd = df.groupby([pd.TimeGrouper(freq="QS-JAN"), 'CD_PDP'])
result = []
for (quarter, unite), data in gpd:
nb_MAT_RH = data["MAT_RH" ].nunique()
nb_MAT_RHPI = data["MAT_RHPI"].nunique()
result.append({"CD_PDP": unite, "MOIS_COMPTABLE": quarter, "nb_mat_rh" : nb_MAT_RH, "nb_MAT_RHPI" : nb_MAT_RHPI})
return pd.DataFrame(result)
def vectorisation(df):
b = df.groupby([pd.TimeGrouper(freq="QS-JAN"), 'CD_PDP']).apply(lambda x: pd.Series( {"nb_mat_rh" : x["MAT_RH" ].nunique(),
"nb_MAT_RHPI" : x["MAT_RHPI"].nunique()}))
return b.reset_index()
when testing :
import timeit
print "loop"
print timeit.timeit(stmt="loop_for(df)",number= 2, setup="from __main__ import loop_for; from __main__ import df")
print "vector"
print timeit.timeit(stmt="vectorisation(df)",number= 2, setup="from __main__ import vectorisation; from __main__ import df")
it gives :
loop
6.83789801598
vector
7.13991713524
A: Doing .nunique() on a SeriesGroupBy object does take advantage of vectorization:
grouped = df.groupby([pd.TimeGrouper(freq="QS-JAN"), 'CD_PDP'])
b = df.groupby('a').agg({'MAT_RH': 'nunique', 'MAT_RHPI': 'nunique'})
b = b.rename(columns={'MAT_RH': 'nb_mat_rh', 'MAT_RHPI': 'nb_MAT_RHPI'})
But without even a sample of your original df it is impossible to run any benchmarks.
| |
doc_23534493
|
"ID","ReleaseYear","CriticPlayerPrefer","n","CountCriticScores","CountUserScores"
"1",1994,"Both",1,5,283
"2",1994,"Critics",0,0,0
"3",1994,"Players",0,0,0
"4",1995,"Both",3,17,506
"5",1995,"Critics",0,0,0
"6",1995,"Players",0,0,0
"7",1996,"Both",18,163,3536
"8",1996,"Critics",2,18,97
"9",1996,"Players",3,20,79
I want to flip the data frame around so the columns are like this:
"ReleaseYear","Both","Critics","Players"
The values for columns Both',CriticsandPlayerswould be then` for each.
When I try running this...
require(dcast)
chartData.CriticPlayerPreferByYear <- dcast(
data = df,
formula = ReleaseYear ~ CriticPlayerPrefer,
fill = 0,
value.var = n
)
... I get this error:
Error in match(x, table, nomatch = 0L) :
'match' requires vector arguments
What is the problem here? How do I fix it?
A: You seem to be missing quotation marks?
data <- read.table(text='"ID","ReleaseYear","CriticPlayerPrefer","n","CountCriticScores","CountUserScores"
"1",1994,"Both",1,5,283
"2",1994,"Critics",0,0,0
"3",1994,"Players",0,0,0
"4",1995,"Both",3,17,506
"5",1995,"Critics",0,0,0
"6",1995,"Players",0,0,0
"7",1996,"Both",18,163,3536
"8",1996,"Critics",2,18,97
"9",1996,"Players",3,20,79"',header=T,sep=",")
library(reshape2)
dcast(data, ReleaseYear ~ CriticPlayerPrefer, value.var="n")
# ReleaseYear Both Critics Players
# 1994 1 0 0
# 1995 3 0 0
# 1996 18 2 3
This is what I get. Is it the desired result?
| |
doc_23534494
|
I want to have an appearance of
1 = 20 times
2 = 30 times
3 = 50 times
A: The principle here is to create a list/array with the values appearing a set number of times, shuffling that list/array and then reshaping it.
The starting point to generate the data:
a = [1 for x in range(20)]
b = [2 for x in range(30)]
c = [3 for x in range(50)]
full_array = a + b + c
A pure python approach might use this slightly adapted:
import random
def chunks(l, n):
n = max(1, n)
return [l[i:i+n] for i in range(0, len(l), n)]
random.shuffle(full_array)
matrix = chunks(full_array, 10)
If you use numpy then things become easier:
import numpy as np
full_array = np.array(full_array)
np.random.shuffle(full_array)
matrix = full_array.reshape(10, 10)
A: I think a one-liner does exist for this. But until then this should work.
import numpy as np
temp=np.hstack((np.array([1]*20), np.array([2]*30), np.array([3]*50)))
np.random.shuffle(temp)
temp=temp.reshape(10, 10)
print(temp)
A: Maybe the best option is use numpy [1]
np.random.randint(5, size=(2, 4))
[1]https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html
| |
doc_23534495
|
I was just wondering if anyone can see any obvious errors that i am missing and could help out with some information int he right direction.
Link to the JSFiddle
//Counting the average temperatures in a day
//needs debugged!!!
var temperatures = [];
var total = 0;
function getCity() {
//get the locale to help with the display
city = prompt("Enter your city >> ");
}
function getNumDays() {
number = prompt("How many days in the study? Enter 1 - 10");
while ((number < 1) || (number > 10) ||( isNaN(number) === true)) {
alert ("Invalid input!");
number = prompt ("Enter again, 1 - 10 >> ");}
return number;
}
function getTemps(numDays) {
total = 0;
for (i = 0; i < numDays; i++) {
next = prompt ("Enter the temperature for day " + (i+1));
next = parseint(next);
while (isNaN(next)===true) {
next = 0;
next = prompt ("Error in input! Try again >>");
next = parseInt(next);}
temperatures.push(next);
}
total = total + next;
return temperatures;
}
function calcAverage(total, numDays) {
average = total / numDays;
return average;
}
function showStatistics(city, average, numdays) {
alert ("The average daily temperature for "+ city + " is " + average.toFixed(2) + " measured over " + numDays + " days." );
}
//main program
city = getCity();
numDays = getNumDays();
temperatures = getTemps(numDays);
Average = calcAverage(total, numDays);
showStatistics(city, average, numDays);
A: function getCity() {
//get the locale to help with the display
city = prompt("Enter your city >> ");
}
//main program
city = getCity();
Looks like you're missing a return statement.
Additionally, the line total = total + next; seems to be out of place: I imagine the total to be the total of the temperatures, not 0 + temperatureOfLastDay.
| |
doc_23534496
|
public class Cube {
public int x, y;
private boolean conflict = false;
public Cube(int x, int y) {
this.x = x;
this.y = y;
}
public void moveDown() {
if(!conflict("down")) {
this.y += 18;
}
}
public boolean conflict(String dir) {
if(dir.equals("down")) {
for(Cube cubes : Panel.cubes) {
if(this.hashCode() != cubes.hashCode()) {
if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
this.conflict = true;
} else this.conflict = false;
}
}
}
}
}
A: First of all your conflict method doesn't return anything, I'm wondering how this compiles. But the problem is you never go out the for loop when you find a collision.
public boolean conflict(String dir) {
if (dir.equals("down")) {
for(Cube cubes : Panel.cubes) {
if(this.hashCode() != cubes.hashCode()) {
if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
this.conflict = true;
break;
} else {
this.conflict = false;
}
}
}
}
return this.conflict;
}
A: It looks like you want to break from the loop when you find a conflict, since otherwise the next iteration may reset that flag (which explains why "collision is working only for last cube in arraylist").
if (dir.equals("down")) {
for(Cube cubes : Panel.cubes) {
if(this.hashCode() != cubes.hashCode()) {
if(this.y + 18 == cubes.y && this.x == cubes.x || this.y >= Main.height - 18*4) {
this.conflict = true;
break;
} else {
this.conflict = false;
}
}
}
}
BTW, your conflict method seems to be missing a return statement.
| |
doc_23534497
|
I have gone to TortoiseGit -> Settings -> General -> Context Menu and made sure that the Clone option is checked:
I am able to clone a repo using git:
git clone user@location.com:Group/repo.git myrepo
I can also get TortoiseGit's clone dialog to open via command line:
TortoiseGitProc.exe /command:clone
but I can't seem to get it to work with TortoiseGit's shell integration.
Does anyone know why the clone option is not showing up?
A: *
*"Hide Menus for unversioned paths" is selected, so no TortoiseGit menu is shown for paths where no git working tree could be found (you need to press shift there)
*Within a working tree (in a non-ignored folder) no clone is available in the context menu. However, with newer versions (IIRC >= 2.2) also for versioned folders the Git clone entry can be shown by pressing Shift while opening the context menu.
If you want to clone a checked out repository, navigate to a clean new directory, right-click and you will see the clone command in the context menu where you can, then, select the path of the repository you want to clone.
A: I found a solution. When I uncheck the Clone... option from the context menu setting dialog, it appears in the shift+right click context menu in the TortoiseGit folder of the context menu will show the Clone... option. (this is also true for the Create repository here... option). This was a bit confusing since the context menu setting dialog's hover tip is "Check those menu entries you want to appear in the top context menu instead of the TortoiseGit submenu". I was expecting them to show up in the top right-click context menu (above the TortoiseGit submenu) but they didn't. By checking those options they were omitted from the TortoiseGit submenu so they seemed to disappear. I can rest easy now that I can find the Clone... and Create repository here... options, but I would still be curious to know why they aren't showing up in the top context menu.
A: before
*** Right mouse button
after
*** Pressing Shift with Right mouse button
A: For those reader who are still looking for solutions in this problem, I hope this link could help you too:
https://github.com/gitextensions/gitextensions/issues/4423#issuecomment-362666877
| |
doc_23534498
|
I tried to add:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
Then I also found an answer using an Array like this, which seems to make sense
filePathCallback: ValueCallback<Array<Uri>>?
However neither worked in the end. I am posting my cleaned-up code as it is now. I can select pictures one by one but not several at a time (note that this works well if I access the URL directly in a browser on Android or on my iOS app..).
package foo.bar.app
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.*
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.onesignal.OneSignal
open class WebActivity : AppCompatActivity() {
companion object {
const val PAGE_URL = "pageUrl"
const val MAX_PROGRESS = 100
// File selector
private var mUploadMessage: ValueCallback<Uri>? = null
private var uploadMessage: ValueCallback<Array<Uri>>? = null
const val FILECHOOSER_RESULTCODE = 1
const val REQUEST_SELECT_FILE = 100
fun newIntent(context: Context, pageUrl: String): Intent {
val intent = Intent(context, WebActivity::class.java)
intent.putExtra(PAGE_URL, pageUrl)
return intent
}
}
var pageUrl: String = ""
private lateinit var binding: ActivityWebBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityWebBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
pageUrl = intent.getStringExtra(PAGE_URL) ?: ""
initWebView()
setWebClient()
loadUrl(appLinkUrl, "")
}
private fun initWebView() {
binding.webView.settings.loadWithOverviewMode = true
binding.webView.settings.useWideViewPort = true
binding.webView.settings.domStorageEnabled = true
binding.webView.settings.databaseEnabled = true
binding.webView.webViewClient = object : WebViewClient() {
override
fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
when (error!!.primaryError) {
SslError.SSL_UNTRUSTED -> handler?.cancel()
SslError.SSL_EXPIRED -> handler?.cancel()
SslError.SSL_IDMISMATCH -> handler?.cancel()
SslError.SSL_NOTYETVALID -> handler?.cancel()
}
//handler?.proceed()
}
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
val url: String = request?.url.toString()
binding.webView.loadUrl(url)
return true
}
// for backward compatibility
override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
binding.webView.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
}
}
}
private fun setWebClient() {
binding.webView.webChromeClient = object : WebChromeClient() {
// File selector
// For Android 4.1
fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
mUploadMessage = uploadMsg
val i = Intent(Intent.ACTION_GET_CONTENT)
i.addCategory(Intent.CATEGORY_OPENABLE)
i.type = "image/*"
this@WebActivity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE)
}
// File selector
protected fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
mUploadMessage = uploadMsg
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE)
}
// File selector
override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
uploadMessage?.onReceiveValue(null)
uploadMessage = null
uploadMessage = filePathCallback
val intent = fileChooserParams!!.createIntent()
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
try {
startActivityForResult(intent, REQUEST_SELECT_FILE)
return true
} catch (e: ActivityNotFoundException) {
uploadMessage = null
Toast.makeText(applicationContext, "Cannot Open File Chooser", Toast.LENGTH_LONG).show()
return false
}
return true
}
}
}
// File selector
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return
print("result code = $resultCode")
val results: Array<Uri>? = WebChromeClient.FileChooserParams.parseResult(resultCode, data)
uploadMessage?.onReceiveValue(results)
uploadMessage = null
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
val result = if (intent == null || resultCode != RESULT_OK) null else intent.data
mUploadMessage?.onReceiveValue(result)
mUploadMessage = null
} else
Toast.makeText(applicationContext, "Failed to Upload Image", Toast.LENGTH_LONG).show()
}
private fun loadUrl(pageUrl: String, postData: String) {
if( postData == "" ) binding.webView.loadUrl(pageUrl)
else binding.webView.postUrl(pageUrl, postData.toByteArray())
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent) {
val appLinkAction = intent.action
val appLinkData: Uri? = intent.data
if (Intent.ACTION_VIEW == appLinkAction) {
if (appLinkData != null) {
appLinkData.path?.let { loadUrl(it, "") }
}
}
}
}
I am trying to manage older Android versions, my objective is to support multiple file uploads in more recents versions at least. I can live without this feature on older versions.
Let me know if you see something I am missing.
Thanks for the help !
C
| |
doc_23534499
|
Can you please suggest how I can achieve it ?
These are the commands which ill be using to get the commit id or tag id :
git log -1 --format=%h
git describe --tags --abbrev=0
A: Commit sha is provided by Gitlab out of the box. You can use bash scripts to achive what you want
before_script:
- if [[ $ENV == "prod" ]]; then export RELEASE_TAG=$(git describe --tags --abbrev=0); else export RELEASE_TAG="$CI_COMMIT_SHA"; fi;
script:
- echo $RELEASE_TAG
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.