I have a problem of running different versions of STS this morning, the application crash with the similar way as the question did.
Excerpt of my log file.
A fatal error has been detected by the Java Runtime Environment:
#a
# SIGSEGV (0xb) at pc=0x00007f459db082a1, pid=4577, tid=139939015632640
#
# JRE version: 6.0_30-b12
# Java VM: Java HotSpot(TM) 64-Bit Server VM
(20.5-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [libsoup-2.4.so.1+0x6c2a1] short+0x11
note that exception occured at # C [libsoup-2.4.so.1+0x6c2a1] short+0x11
Okay then little below the line:
R9 =0x00007f461829e550: <offset 0xa85550> in /usr/share/java/jdk1.6.0_30/jre/lib/amd64/server/libjvm.so at 0x00007f4617819000
R10=0x00007f461750f7c0 is pointing into the stack for thread: 0x00007f4610008000
R11=0x00007f459db08290: soup_session_feature_detach+0 in /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1 at 0x00007f459da9c000
R12=0x0000000000000000 is an unknown value
R13=0x000000074404c840 is an oop
{method}
This line tells you where the actual bug or crash is to investigate more on this crash issue please use below links to see more, but let's continue the crash investigation and how I resolved it and the novelty of this bug :)
links are :
a fATAL ERROR JAVA THIS ONE IS GREAT LOTS OF USER!
Okay, after that here's what I found out to casue this case and why it happens as general advise.
Most of the time, check that if you have installed, updated recently on Ubunu and Windows there are libraries like libsoup in linux which were the casuse of my crash.
Check also for a new hardware problem and try to investigate the Logfile
which STS
or Java
generated and also syslog
in linux
by
tail - f /var/lib/messages or some other file
Then by carfully looking at those files the one you have the crash log for ... you can really solve the issue as follows:
sudo unlink /usr/lib/i386-linux-gnu/libsoup-2.4.so.1
or
sudo unlink /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1
Done !! Cheers!!
DECLARE @EndTime AS DATETIME, @StartTime AS DATETIME
SELECT @StartTime = '2013-03-08 08:00:00', @EndTime = '2013-03-08 08:30:00'
SELECT CAST(@EndTime - @StartTime AS TIME)
Result: 00:30:00.0000000
Format result as you see fit.
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
The simplest possible way to do this is the following:
In the Controller method you need to extract the body from, add this parameter: [FromBody] SomeClass value
Declare the "SomeClass" as: class SomeClass { public string SomeParameter { get; set; } }
When the raw body is sent as json, .net core knows how to read it very easily.
I think you're looking for the intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect()
returns an array containing all values of array1 that are
present in all the arguments. Note that keys are preserved.
Exact solution to your problem
You can change the image on hover by using content:url("YOUR-IMAGE-PATH");
For image hover use below line in your css:
img:hover
and to change the image on hover using the below config inside img:hover:
img:hover{
content:url("https://www.planwallpaper.com/static/images/9-credit-1.jpg");
}
Here is the simplest python socket example.
Server side:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections
while True:
connection, address = serversocket.accept()
buf = connection.recv(64)
if len(buf) > 0:
print buf
break
Client Side:
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector
.class {
margin:20px;
&:hover {
color:yellow;
}
}
In addition to Shayne3000's answer you can also use a color resource (not only an int color). Kotlin version:
var indicatorViewDrawable = itemHolder.indicatorView.background
indicatorViewDrawable = DrawableCompat.wrap(indicatorViewDrawable)
val color = ResourcesCompat.getColor(context.resources, R.color.AppGreenColor, null) // get your color from resources
DrawableCompat.setTint(indicatorViewDrawable, color)
itemHolder.indicatorView.background = indicatorViewDrawable
Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.
First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?
If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).
HTH
As a more general solution you might want to check out the Microsoft Power Toy for XP that adds the "Open Command Window Here" option when you right-click: http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
In Vista and Windows 7, you'll get that option if you hold down shift and right-click (this is built in).
To minimize the duty of the server make it simple:
.htaccess
ErrorDocument 403 "Forbidden"
PHP
header('HTTP/1.0 403 Forbidden');
die(); // or your message: die('Forbidden');
If order is preserved between files you might also prefer difflib
. Although Rob?'s result is the bona-fide standard for intersections you might actually be looking for a rough diff-like:
from difflib import Differ
with open('cfg1.txt') as f1, open('cfg2.txt') as f2:
differ = Differ()
for line in differ.compare(f1.readlines(), f2.readlines()):
if line.startswith(" "):
print(line[2:], end="")
That said, this has a different behaviour to what you asked for (order is important) even though in this instance the same output is produced.
public static void hanoi(int number, String source, String aux, String dest)
{
if (number == 1)
{
System.out.println(source + " - > "+dest);
}
else{
hanoi(number -1, source, dest, aux);
hanoi(1, source, aux, dest);
hanoi(number -1, aux, source, dest);
}
}
Thank you Joel for giving me a clue on how to resolve this problem.
I have simplified the code(without need for a GestureDetector) to achieve the same effect:
public class VerticalScrollView extends ScrollView {
private float xDistance, yDistance, lastX, lastY;
public VerticalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDistance = yDistance = 0f;
lastX = ev.getX();
lastY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
xDistance += Math.abs(curX - lastX);
yDistance += Math.abs(curY - lastY);
lastX = curX;
lastY = curY;
if(xDistance > yDistance)
return false;
}
return super.onInterceptTouchEvent(ev);
}
}
For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:
Using Windows Explorer, navigate to:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013
In that folder, you'll see a shortcut named Visual Studio Tools
that maps to (assuming default installation):
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
Double-click the shortcut (or go to the folder above).
From that folder, copy the shortcut named Developer Command Prompt for VS2013
(and any others you find useful) to the first directory (for the Start Menu
). You'll likely be prompted for administrative access (do so).
Once you've done that, you'll now have an icon available for the 2013 command prompt.
I wrote a program with wpf
and used Database for showing images and this is my code:
SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
Initial Catalog=Payam;
Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from news", con);
DataTable dt = new DataTable();
da.Fill(dt);
string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
Frameworks usually use bracket names in forms, like:
<input name=user[first_name] />
They can be accessed by:
// in JS:
this.querySelectorAll('[name="user[first_name]"]')
// in jQuery:
$('[name="user[first_name]"]')
// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.
A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)
just change the path:
"c:\program files\android\sdk" to "c:\progra~1\android\sdk"
or
"c:\program files (x86)\android\sdk" to "c:\progra~2\android\sdk"
note that the paths should not contain spaces.
Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:
/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while let pVC = presentedVC?.presentedViewController {
presentedVC = pVC
}
if presentedVC == nil {
print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
}
return presentedVC
}
Its included as a standard function in:
I know that it could be done with a FOR but I wanted to know if there's another way
There is another way. You can also do it with map and itemgetter:
>>> from operator import itemgetter
>>> map(itemgetter(1), elements)
This still performs a loop internally though and it is slightly slower than the list comprehension:
setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
Results:
Method 1: 1.25699996948 Method 2: 1.46600008011
If you need to iterate over a list then using a for
is fine.
You can use the following CTE as well. You can just modify it as you find fit. But this will add the same values into the student CTE.
This will add 1000 records but you can change it to 10000 or to a maximum of 32767
;WITH thetable(rowid,sname,semail,spassword) AS
(
SELECT 1 , 'name' , 'email' , 'password'
UNION ALL
SELECT rowid+1 ,'name' , 'email' , 'password'
FROM thetable WHERE rowid < 1000
)
SELECT rowid,sname,semail,spassword
FROM thetable ORDER BY rowid
OPTION (MAXRECURSION 1000);
The current alternative for pluck()
is value()
.
I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run
, config
, service
, factory
, etc..), which are more professional.In this function you don't even have to inject that by yourself like
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
you can use it, as you know.
Using setBackgroundColor() affects the style. So, declare a new style of the same properties with respect to the previous button, with a a different color.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>
Now, use OnClick method.
location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
location.setBackgroundResource(R.drawable.green);
}
});
this changes the button but looks similar to changing the background.
If you put #!/bin/awk -f
on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)
#!/bin/awk -f
BEGIN {} # Begin section
{} # Loop section
END{} # End section
Change the file to be executable by running:
chmod ugo+x ./awk-script
and you can then call your AWK script like this:
`$ echo "something" | ./awk-script`
I was using Terminator before, so I found it convenient to re-map Alt + arrow-key to switch between the panes. This can be done in Preferences -> Keys -> Key Mappings - press the '+' button to add a mapping. Also, in my case such a mapping was already defined in Profiles, I simply removed it.
You can control the data returned from SQL database by ordering the data returned:
orderby [Name]
If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.
Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.
That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).
Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.
Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.
There are possible ways to decompile Java programs. You can use dex2jar
, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.
However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.
The tools are always out there. But the conscience, unfortunately, not always.
edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
On Mac OS X, the Xcode developer suite includes the USB Proper.app application. This is found in /Developer/Applications/Utilities/. USB Prober will allow you to examine the device and interface descriptors.
Why not just remove that attribute?
elem.removeAttribute('disabled')
elem.removeAttr('disabled')
'*' works as a modifier for the previous item. So 'abc*def' searches for 'ab' followed by 0 or more 'c's follwed by 'def'.
What you probably want is 'abc.*def' which searches for 'abc' followed by any number of characters, follwed by 'def'.
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
ihave followed the instruction of heroku logs img https://devcenter.heroku.com/articles/buildpacks#detection-failure ( use cmd: heroku logs -> show your error) then do the cmd: "heroku buildpacks:clear". finally, it worked for me!
In Visual Studio Code open 'user settings': ctrl + p
and type >sett
press enter
This will open default settings on left side and User settings on right side.
Just add path to git.exe in user settings
"git.path": "C:\\Users\\[WINDOWS_USER]\\AppData\\Local\\Programs\\Git\\bin\\git.exe"
Replace [WINDOWS_USER] with your user name.
Restart Visual Studio Code
If you're using React Js for your website, use https://www.npmjs.com/package/react-device-detect
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
In addressing your comment that you need your current time, and not the system time, you will have to make an adjustment yourself, there are 3600 seconds in an hour (the unit timestamps use), so use that. for example, if your system time was one hour behind:
$time = date('H:i',time() + 3600);
Ok, for this first of all you need to use Device Policy Manager, and need to make your device Admin device. After that you have to create one BroadCast receiver and one service. I am posting code here and its working fine.
MainActivity:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
private DevicePolicyManager mDPM;
private ComponentName mAdminName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mAdminName = new ComponentName(this, DeviceAdminDemo.class);
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Click on Activate button to secure your application.");
startActivityForResult(intent, REQUEST_CODE);
} else {
// mDPM.lockNow();
// Intent intent = new Intent(MainActivity.this,
// TrackDeviceService.class);
// startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode) {
Intent intent = new Intent(MainActivity.this, TService.class);
startService(intent);
}
}
}
//DeviceAdminDemo class
public class DeviceAdminDemo extends DeviceAdminReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void onEnabled(Context context, Intent intent) {
};
public void onDisabled(Context context, Intent intent) {
};
}
//TService Class
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
private Handler handler;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
//Permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
//my_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
//Declare following thing in manifest:
Declare DeviceAdminDemo class to manifest:
<receiver
android:name="com.example.voicerecorder1.DeviceAdminDemo"
android:description="@string/device_description"
android:label="@string/device_admin_label"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/my_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
</receiver>
<service android:name=".TService" >
</service>
div {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
-ms-transform: translate(-50%, -50%); /* IE 9 */_x000D_
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ _x000D_
}
_x000D_
<body>_x000D_
<div>Div to be aligned vertically</div>_x000D_
</body>
_x000D_
position: absolute div in body document
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
source: CSS position
use like this your inline css
<td width="178" rowspan="3" valign="top"
align="right" background="images/left.jpg"
style="background-repeat:background-position: right top;">
</td>
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
Why not use an object1?
var dict = { "a": 1, "b": 2, "c": 3 };
Then you can update it like so
dict.a = 23;
or
dict["a"] = 23;
If you wan't to delete2 a particular key, it's as simple as:
delete dict.a;
1 See Objects vs arrays in Javascript for key/value pairs.
2 See the delete
operator.
if you are using bigint in your database table, you can use Long in C#
You could create Util class:
public final class CollectionHelpers {
public static <T> boolean addNullSafe(List<T> list, T element) {
if (list == null || element == null) {
return false;
}
return list.add(element);
}
}
And then use it:
Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);
\
does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.
Consider this command:
mysql -uroot \ -hlocalhost
If there is a space after \
, the line continuation will not work. The reason is that \
removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \
in this example.
This will match one or more alphabetical characters:
/^[a-z]+$/
You can make it case insensitive using:
/^[a-z]+$/i
or:
/^[a-zA-Z]+$/
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();
To have it send it as a CSV and have it give the file name, use header():
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.
To select columns to plot, I added 2 lines to Vincent Zoonekynd's answer:
#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")
#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
geom_point() +
geom_smooth()
Google "tidy data" to know more about tall(or long)/wide format.
If direct casting shows error you can do it like this:
Long id = 100;
int int_id = (int) (id % 100000);
I use namespaces:
var Foo = {
element: document.getElementById("id-here"),
Talk: function(message) {
alert("talking..." + message);
},
ChangeElement: function() {
this.element.style.color = "red";
}
};
And to use it:
Foo.Talk("Testing");
Or
Foo.ChangeElement();
Here's a macro that allows you to shuffle selected cells in a column:
Option Explicit
Sub ShuffleSelectedCells()
'Do nothing if selecting only one cell
If Selection.Cells.Count = 1 Then Exit Sub
'Save selected cells to array
Dim CellData() As Variant
CellData = Selection.Value
'Shuffle the array
ShuffleArrayInPlace CellData
'Output array to spreadsheet
Selection.Value = CellData
End Sub
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim J As Long, _
N As Long, _
Temp As Variant
'Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If J <> N Then
Temp = InArray(N, 1)
InArray(N, 1) = InArray(J, 1)
InArray(J, 1) = Temp
End If
Next N
End Sub
You can read the comments to see what the macro is doing. Here's how to install the macro:
Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).
Here is a sub-optimal solution as a one-liner:
Collections.list(Collections.enumeration(coll));
In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
I have a simpler solution for you:
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
and to get it :
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(getLocalClassName(), "onItemClick(" + view + ","
+ position + "," + id + ")");
}
});
Have you tried Visual Assist X ? Sort of lights up the VS editor.
The main difference between return false
and event.preventDefault()
is that your code below return false
will not be executed and in event.preventDefault()
case your code will execute after this statement.
When you write return false it do the following things for you behind the scenes.
* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();
You can use the listings package. It supports many different languages and there are lots of options for customising the output.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
It's because you're missing position:relative;
on #contentframe
<div id="contentframe" style="position:relative; top: 160px; left: 0px;">
position:absolute;
positions itself against the closest ancestor that has a position
that is not static
. Since the default is static
that is what was causing your issue.
As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.
Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,
int main()
{
int a = func();
}
int func()
{
return 1;
}
However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.
int func();
int main()
{
int a = func();
}
int func()
{
return 1;
}
Using the AWS Management Console
Assuming you wanted to overwrite the previous value of the object referred to by a
, then a member function would have to be invoked.
Complex a, b, c;
// ...
a = b.add(c);
In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and copy the resultant value from the temporary object into the existing object a
.
However, in Java, operator=
doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named Complex
, assignment means to copy a reference to an existing value.
Consider instead:
b.set(1, 0); // initialize to real number '1'
a = b;
b.set(2, 0);
assert( !a.equals(b) ); // this assertion will fail
In C++, this copies the value, so the comparison will result not-equal. In Java, operator=
performs reference copy, so a
and b
are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.
The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+
would likely deal with values and objects, but operator=
is already implemented to deal with references.
In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex
, operator=
and operator==
are both working on values -- copying values and comparing values respectively.
document.getElementById('r1').innerHTML = dayjs('sdsdsd').isValid()_x000D_
_x000D_
document.getElementById('r2').innerHTML = dayjs('2/6/20').isValid()
_x000D_
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>_x000D_
_x000D_
<p>'sdsdsd' is a date: <span id="r1"></span></p>_x000D_
<p>'2/6/20' is a date: <span id="r2"></span></p>
_x000D_
A light weight library is ready for you: Day.js
If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date
constructor is not supported pre IE9:
var queryDate = '2009-11-01',
dateParts = queryDate.match(/(\d+)/g)
realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
// months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');
$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);
Check the above example here.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:
let imagen = ev.target.getAttribute('src');
arrayImagenes.push(imagen);
SELECT T.TABLE_NAME, C.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
AND COLUMN_NAME = 'ColName'
This returns tables only and ignores views for anyone who is interested!
"The problem is that i cant find a way to set a fixed number of rows"
You don't need to set the number of rows. Use a TableModel
. A DefaultTableModel
in particular.
String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
// The 0 argument is number rows.
JTable table = new JTable(tableModel);
Then you can add rows to the tableModel
with an Object[]
Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};
tableModel.addRow(objs);
You can loop to add your Object[] arrays.
Note: JTable does not currently allow instantiation with the input data as an ArrayList
. It must be a Vector
or an array.
See JTable and DefaultTableModel. Also, How to Use JTable tutorial
"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."
You can do something like this to add the data
ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();
originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));
for (int i = 0; i < originalLeagueList.size(); i++){
int position = originalLeagueList.get(i).getPosition();
String name = originalLeagueList.get(i).getName();
int points = originalLeagueList.get(i).getPoinst();
int wins = originalLeagueList.get(i).getWins();
int defeats = originalLeagueList.get(i).getDefeats();
int draws = originalLeagueList.get(i).getDraws();
int totalMatches = originalLeagueList.get(i).getTotalMathces();
int goalF = originalLeagueList.get(i).getGoalF();
int goalA = originalLeagueList.get(i).getGoalA();
in ttgoalD = originalLeagueList.get(i).getTtgoalD();
Object[] data = {position, name, points, wins, defeats, draws,
totalMatches, goalF, goalA, ttgoalD};
tableModel.add(data);
}
you can use pass inside if statement.
package article14;
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;
public class Pdf
{
public static void main(String args[])
{
new Pdf().createNew();
new Pdf().combine();
}
public void combine()
{
try
{
PDFMergerUtility mergePdf = new PDFMergerUtility();
String folder ="pdf";
File _folder = new File(folder);
File[] filesInFolder;
filesInFolder = _folder.listFiles();
for (File string : filesInFolder)
{
mergePdf.addSource(string);
}
mergePdf.setDestinationFileName("Combined.pdf");
mergePdf.mergeDocuments();
}
catch(Exception e)
{
}
}
public void createNew()
{
PDDocument document = null;
try
{
String filename="test.pdf";
document=new PDDocument();
PDPage blankPage = new PDPage();
document.addPage( blankPage );
document.save( filename );
}
catch(Exception e)
{
}
}
}
Just make regular link look like button :)
<a href="#" role="button" class="btn btn-success btn-large">Click here!</a>
"role" inside a href code makes it look like button, ofc you can add more variables such as class.
Best way to avoid OOM during Bitmap creation,
http://developer.android.com/training/displaying-bitmaps/index.html
I'm going to put this in here more for completeness than direct relevance to the OP. I spent nearly a day debugging an HttpClient
request, wondering why I was never getting back a response.
Finally found that I had forgotten to await
the async
call further down the call stack.
Feels about as good as missing a semicolon.
legend.green-color{_x000D_
color:green !important;_x000D_
}
_x000D_
inspired by Sammys answer above:
margins = { # vvv margin in inches
"left" : 1.5 / figsize[0],
"bottom" : 0.8 / figsize[1],
"right" : 1 - 0.3 / figsize[0],
"top" : 1 - 1 / figsize[1]
}
fig.subplots_adjust(**margins)
Where figsize is the tuple that you used in fig = pyplot.figure(figsize=...)
Change this line:
The 2 should be 0. Every count starts at 0.
//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong
//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct
Check whether its the jpg, png, bmp file that you are providing and write the extension accordingly.
IF EXISTS(SELECT 1 FROM sys.types WHERE name = 'Person' AND is_table_type = 1 AND SCHEMA_ID('VAB') = schema_id)
DROP TYPE VAB.Person;
go
CREATE TYPE VAB.Person AS TABLE
( PersonID INT
,FirstName VARCHAR(255)
,MiddleName VARCHAR(255)
,LastName VARCHAR(255)
,PreferredName VARCHAR(255)
);
The folder being password protected has nothing to do with PHP!
The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...
Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess
or wherever it is first):
login.php:
<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
$_SESSION['logged_in'] = true;
header('Location: /index.php');
}
else
{
?>
<form method="POST">
Username: <input name="user" type="text"><br>
Password: <input name="pass" type="text"><br><br>
<input type="submit" value="submit">
</form>
<?php
}
index.php
<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
?>
<p>here is my super-secret content</p>
<a href='logout.php'>Click here to log out</a>
<?php
}
else
{
echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}
logout.php:
<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';
Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.
Hope this helps you understand what's going on.
This is the best I've found for teaching new programmers, and without using additional libraries. I'd like something better though.
def initialize_twodlist(value):
list=[]
for row in range(10):
list.append([value]*10)
return list
Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)
The <prev>
-tag might be an XML-tag.
You can effectively remove scientific notation in printing with this code:
options(scipen=999)
Here is the definition of a bare repository from gitglossary:
A bare repository is normally an appropriately named directory with a .git suffix that does not have a locally checked-out copy of any of the files under revision control. That is, all of the Git administrative and control files that would normally be present in the hidden .git sub-directory are directly present in the repository.git directory instead, and no other files are present and checked out. Usually publishers of public repositories make bare repositories available.
I arrived here because I was playing around with a "local repository" and wanted to be able to do whatever I wanted as if it were a remote repository. I was just playing around, trying to learn about git. I'll assume that this is the situation for whoever wants to read this answer.
I would love for an expert opinion or some specific counter-examples, however it seems that (after rummaging through some git source code that I found) simply going to the file .git/config
and setting the core attribute bare to true, git will let you do whatever you want to do to the repository remotely. I.e. the following lines should exist in .git/config
:
[core]
...
bare = true
...
(This is roughly what the command git config --bool core.bare true
will do, which is probably recommended to deal with more complicated situations)
My justification for this claim is that, in the git source code, there seems to be two different ways of testing if a repo is bare or not. One is by checking a global variable is_bare_repository_cfg
. This is set during some setup phase of execution, and reflects the value found in the .git/config
file. The other is a function is_bare_repository()
. Here is the definition of this function:
int is_bare_repository(void)
{
/* if core.bare is not 'false', let's see if there is a work tree */
return is_bare_repository_cfg && !get_git_work_tree();
}
I've not the time nor expertise to say this with absolute confidence, but as far as I could tell if you have the bare
attribute set to true
in .git/config
, this should always return 1
. The rest of the function probably is for the following situation:
I'll experiment with it when I can later, but this would seem to indicate that setting core.bare = true is equivalent to removeing core.bare from the config file and setting up the directories properly.
At any rate, setting core.bare = true certainly will let you push to it, but I'm not sure if the presence of project files will cause some other operations to go awry. It's interesting and I suppose instructive to push to the repository and see what happened locally (i.e. run git status
and make sense of the results).
dG will delete from the current line to the end of file
dCtrl+End will delete from the cursor to the end of the file
But if this file is as large as you say, you may be better off reading the first few lines with head
rather than editing and saving the file.
head hugefile > firstlines
(If you are on Windows you can use the Win32 port of head
)
public void clear(StringBuilder s) {
s.setLength(0);
}
Usage:
StringBuilder v = new StringBuilder();
clear(v);
for readability, I think this is the best solution.
above answers In simple words,
you have to register under @NgModule
's
declarations: [
AppComponent, YourNewComponentHere
]
of app.module.ts
do not forget to import
that component.
Try the following:
if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
update PageImage
set VisitCount=1
where PID=@pid and PageNumber=@pageno
end
else
begin
update PageImage
set VisitCount=VisitCount+1
where PID=@pid and PageNumber=@pageno
end
To search google using API you should use Google Custom Search, scraping web page is not allowed
In java you can use CustomSearch API Client Library for Java
The maven dependency is:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-customsearch</artifactId>
<version>v1-rev57-1.23.0</version>
</dependency>
Example code searching using Google CustomSearch API Client Library
public static void main(String[] args) throws GeneralSecurityException, IOException {
String searchQuery = "test"; //The query to search
String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine
//Instance Customsearch
Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null)
.setApplicationName("MyApplication")
.setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key"))
.build();
//Set search parameter
Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx);
//Execute search
Search result = list.execute();
if (result.getItems()!=null){
for (Result ri : result.getItems()) {
//Get title, link, body etc. from search
System.out.println(ri.getTitle() + ", " + ri.getLink());
}
}
}
As you can see you will need to request an api key and setup an own search engine id, cx.
Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.
Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.
It is a good practice to set where the access log should be in nginx configuring file . Using acces_log /path/ Like this.
keyval $remote_addr:$http_user_agent $seen zone=clients;
server { listen 443 ssl;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
if ($seen = "") {
set $seen 1;
set $logme 1;
}
access_log /tmp/sslparams.log sslparams if=$logme;
error_log /pathtolog/error.log;
# ...
}
The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.
To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.
It cannot be accomplished with css font-size
Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.
I know it's a little late response, but I got the same problem a couple of days before and I have came with a nice & smooth solution. First I found this great date picker here
Then I've just updated the CSS class (jquery.calendarPicker.css) that comes with the example like this:
.calMonth {
/*border-bottom: 1px dashed #666;
padding-bottom: 5px;
margin-bottom: 5px;*/
}
.calDay
{
display:none;
}
The plugin fires an event DateChanged when you change anything, so it doesn't matter that you are not clicking on a day (and it fits nice as a year and month picker)
Hope it helps!
Delete the artifacts (or the full local repo) from c:\Users\<username>\.m2\repository
by hand.
2 more helpful methods: System.Environment.GetEnvironmentVariable("ComputerName" )
System.Environment.GetEnvironmentVariable("ClientName" ) to get the name of the user's PC if they're connected via Citrix XenApp or Terminal Services (aka RDS, RDP, Remote Desktop)
I am late for the answer but I think this is another solution which is not mentioned here so posting.
Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.
filter.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/action_filter"
android:title="@string/filter"
android:orderInCategory="10"
android:icon="@drawable/filter"
app:showAsAction="ifRoom" />
</menu>
Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Step 3: Now add the method onCreateOptionsMenu which will be override as:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu); // Use filter.xml from step 1
}
Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_filter){
//Do whatever you want to do
return true;
}
return super.onOptionsItemSelected(item);
}
And don't forget to create a __init__.py
with each folder/subfolder (even if they are empty)
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
For those who need convert minutes to time with more than 24h format:
DECLARE @minutes int = 7830
SELECT CAST(@minutes / 60 AS VARCHAR(8)) + ':' + FORMAT(@minutes % 60, 'D2') AS [Time]
Result:
130:30
A fast way of doing this is to clone using the --bare
keyword and then check the log:
git clone --bare git@giturl tmpdir
cd tmpdir
git log branch
Directly changing eclipse file is not a good idea, no matter facet or ini, unless it could be changed in eclipse. Had the same problem, with jdk1.8 installed. Change it to jdk 1.7.
Besides, according to https://wiki.eclipse.org/Eclipse/Installation, both LUNA and MARS need 1.7. So just ensure you have it installed.
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
in eclipse, right click project, select RunAs -> Run Configuration and save your run configuration, this will be used when you next export as Runnable JARs
To make UILabel fit the dynamic content you can use lines property in property inspector and set that as 0.
And you don't require to do any coding for this.
For more details you can check below demonstration video
Hope you are using Python 3 ,
Str are unicode by default, so please
Replace Unicode
function with String Str
function.
if isinstance(unicode_or_str, str): ##Replaces with str
text = unicode_or_str
decoded = False
Use ..
to indicate the parent directory:
background-image: url('../images/bg.png');
Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:
if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
cell_value = cell_value.replaceAll("\"", "\"\"");
row.append("\"");
row.append(cell_value);
row.append("\"");
} else {
row.append(cell_value);
}
in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\""
) by adding additional double quote (like "\"\""
), then put the whole thing into a double quote (like "\""+theWholeThing+"\""
)
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
I have faced some scenarios where above answers dint work for me. So i came up with this. Might be helpful to someone.
if(/iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent)
|| screen.availWidth < 480){
//code for mobile
}
It depends on your use case. If you focus on screen use screen.availWidth
, or you can use document.body.clientWidth
if you want to render based on document.
This following:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
def _x_set(self, value):
self._x = value
def _x_del(self):
del self._x
x = property(_x_get, _x_set, _x_del,
"I'm the 'x' property.")
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
def _x_set(self, value):
self._x = value
def _x_del(self):
del self._x
x = property(_x_get, doc="I'm the 'x' property.")
x = x.setter(_x_set)
x = x.deleter(_x_del)
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
x = property(_x_get, doc="I'm the 'x' property.")
def _x_set(self, value):
self._x = value
x = x.setter(_x_set)
def _x_del(self):
del self._x
x = x.deleter(_x_del)
Which is the same as :
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Swift 3 : Xcode 8 helper function:
func getDayOfWeek(fromDate date: Date) -> String? {
let cal = Calendar(identifier: .gregorian)
let dayOfWeek = cal.component(.weekday, from: date)
switch dayOfWeek {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
return nil
}
}
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'.
In perl $foo
is the name of the variable.
I think it's so difficult to do this in Python because of the simple fact that you never will not know the name of the variable you're using. So, in his example, you could do:
Instead of:
list_of_dicts = [n_jobs, users, queues, priorities]
dict_of_dicts = {"n_jobs" : n_jobs, "users" : users, "queues" : queues, "priorities" : priorities}
CONVERT(datetime, '24.04.2012', 104)
Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)
<form>
syn<input type="checkbox" name="checkfield" id="g01-01" />
</form>
js:
$('#g01-01').on('change',function(){
var _val = $(this).is(':checked') ? 'checked' : 'unchecked';
alert(_val);
});
I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.
It works (refreshes the graphs) if I put
plt.clf()
plt.cla()
plt.close()
after every plt.show()
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
Or you can use print_r
if you don't care about types. If you use print_r
, you can make the second argument TRUE
so it will return instead of echo, useful for...
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
dest = source.Substring(0, source.Length - 1);
}
The standard answer to these questions is to use Joda Time. The API is better and if you're using the formatters and parsers you can avoid the non-intuitive lack of thread safety of SimpleDateFormat
.
Using Joda means you can simply do:
LocalDate d = new LocalDate();
Update:: Using java 8 this can be acheived using
LocalDate date = LocalDate.now();
I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:
a2enmod headers
Adding the following directive to our Apache VirtualHost configurations:
Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"
And restarting Apache:
service apache2 restart
In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
You could use memset, if you sure about the length.
memset(ptr, 0x00, length)
Using filter
, you'd just need one line
line = filter(lambda char: char not in " ?.!/;:", line)
This treats the string as an iterable and checks every character if the lambda
returns True
:
>>> help(filter) Help on built-in function filter in module __builtin__: filter(...) filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
On Android 4.4 KitKat, I found mine in:
/sdcard/Android/data/<app.package.name>
If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:
android:background="@android:color/black"
There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.
Setting up a values/colors.xml file and using straight Hex like explained above will still work.
I don't think there's anything wrong with either solutions you proposed in your question.
In my own code, I would implement it like this though:
(x for x in seq if predicate(x)).next()
The syntax with ()
creates a generator, which is more efficient than generating all the list at once with []
.
body {
background: url(images/image_name.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Here is a good solution to get your image to cover the full area of the web app perfectly
If you are reusing an element over and over (A bootstrap modal dialog in my case), then calling ko.applyBindings(el)
multiple times will cause this problem.
Instead just do it once like this:
if (!applied) {
ko.applyBindings(el);
applied = true;
}
Or like this:
var apply = function (viewModel, containerElement) {
ko.applyBindings(viewModel, containerElement);
apply = function() {}; // only allow this function to be called once.
}
PS: This might happen more often to you if you use the mapping plugin and convert your JSON data to observables.
There is easy way of doing this. I don't know why people are giving complicated answers.
Double click SSIS package. Then go to connection manager, select DestinationConnectionOLDB and then add password next to login field.
Example: Data Source=SysproDB1;User ID=test;password=test;Initial Catalog=ASBuiltDW;Provider=SQLNCLI11;Auto Translate=false;
Do same for SourceConnectionOLDB.
Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out:
public static class RolesConvention
{
public const string Administrator = "Administrator";
public const string Guest = "Guest";
}
Then in the controller:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller
You might want to replace <br/>
and </p>
tags with newlines before stripping the HTML to prevent it becoming an illegible mess as Tim suggests.
The only way I can think of removing HTML tags but leaving non-HTML between angle brackets would be check against a list of HTML tags. Something along these lines...
replaceAll("\\<[\s]*tag[^>]*>","")
Then HTML-decode special characters such as &
. The result should not be considered to be sanitized.
Yep, it's a small mistake.
if(this.items.indexOf(item) === -1) {
this.items.push(item);
console.log(this.items);
}
Another way of looking at this is using POSIX ACLs, it needs to be supported by your file system, however you can have fine-grained tuning of all commands in linux the same way you have the same control on Windows (just without the nicer UI). link
Another thing to look into is PolicyKit.
You'll have to do quite a bit of googling to get everything working as this is definitely not a strength of Linux at the moment.
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
As SQLite has limited support to ALTER TABLE so you can only ADD column at end of the table OR CHANGE TABLE_NAME in SQLite.
Here is the Best Answer of HOW TO DELETE COLUMN FROM SQLITE?
http://pchart.sourceforge.net/ looks very good and it's free.
The basic suggestion is to follow REST principles and the following points ties some of these principals to the ASP.NET MVC framework:
Wipe Data
and restart the virtual device again fix the issue in my case.
The sieve of Atkin is an optimized version of the sieve of Eratosthenes which gives all prime numbers up to a given integer. You should be able to google this for more detail.
Once you have that list, it's a simple matter to divide your number by each prime to see if it's an exact divisor (i.e., remainder is zero).
The basic steps calculating the divisors for a number (n) are [this is pseudocode converted from real code so I hope I haven't introduced errors]:
for z in 1..n:
prime[z] = false
prime[2] = true;
prime[3] = true;
for x in 1..sqrt(n):
xx = x * x
for y in 1..sqrt(n):
yy = y * y
z = 4*xx+yy
if (z <= n) and ((z mod 12 == 1) or (z mod 12 == 5)):
prime[z] = not prime[z]
z = z-xx
if (z <= n) and (z mod 12 == 7):
prime[z] = not prime[z]
z = z-yy-yy
if (z <= n) and (x > y) and (z mod 12 == 11):
prime[z] = not prime[z]
for z in 5..sqrt(n):
if prime[z]:
zz = z*z
x = zz
while x <= limit:
prime[x] = false
x = x + zz
for z in 2,3,5..n:
if prime[z]:
if n modulo z == 0 then print z
Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div
elements.
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
Use a changeset. You can add as many files as you like to the changeset, all at once, or over several commands; and then commit them all in one go.
I want to add that there is another difference. It is related to what Andrew posts.
It is also related to a VERY annoying to find bug in our software. See the following simplified example (I also omitted the null check).
public const int SPECIAL_NUMBER = 213;
public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
return numberTextBoxTextValue.Equals(SPECIAL_NUMBER)
}
This will compile and always return false
. While the following will give a compile error:
public const int SPECIAL_NUMBER = 213;
public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
return (numberTextBoxTextValue == SPECIAL_NUMBER);
}
We have had to solve a similar problem where someone compared enums of different type using Equals
. You are going to read over this MANY times before realising it is the cause of the bug. Especially if the definition of SPECIAL_NUMBER
is not near the problem area.
This is why I am really against the use of Equals in situations where is it not necessary. You lose a little bit of type-safety.
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
See : jQuery.ajax()
If you don't know the row number, but do know some values then you can use subset
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5 ),
B = c(4.25, 4, 4, 4.5, 4.5 ),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
subset(x, A ==5 & B==4.25 & C==4.5)
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
Using new "Counter" class in collections module, based on lazyr's answer:
>>> import collections
>>> def duplicates(n): #n="123123123"
... counter=collections.Counter(n) #{'1': 3, '3': 3, '2': 3}
... dups=[i for i in counter if counter[i]!=1] #['1','3','2']
... result={}
... for item in dups:
... result[item]=[i for i,j in enumerate(n) if j==item]
... return result
...
>>> duplicates("123123123")
{'1': [0, 3, 6], '3': [2, 5, 8], '2': [1, 4, 7]}
Both forms of the meta charset declaration are equivalent and should work the same across browsers. But, there are a few things you need to remember when declaring your web files character-set as UTF-8:
Apache servers are configured to serve files in ISO-8859-1 by default, so you need to add the following line to your .htaccess
file:
AddDefaultCharset UTF-8
This will configure Apache to serve your files declaring UTF-8 encoding in the Content-Type response header, but your files must be saved in UTF-8 (without BOM) to begin with.
Notepad cannot save your files in UTF-8 without the BOM. A free editor that can is Notepad++. On the program menu bar, select "Encoding > Encode in UTF-8 without BOM". You can also open files and re-save them in UTF-8 using "Encoding > Convert to UTF-8 without BOM".
More on the Byte Order Mark (BOM) at Wikipedia.
There is a way to do this without explicitly setting your SHELL variable to point to bash. This can be useful if you have many makefiles since SHELL isn't inherited by subsequent makefiles or taken from the environment. You also need to be sure that anyone who compiles your code configures their system this way.
If you run sudo dpkg-reconfigure dash
and answer 'no' to the prompt, your system will not use dash as the default shell. It will then point to bash (at least in Ubuntu). Note that using dash as your system shell is a bit more efficient though.
The word check_
in the name means that if the command (the shell in this case that returns the exit status of the last command (yum
in this case)) returns non-zero status then it raises CalledProcessError
exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_
methods. You could use subprocess.call
in your case because you are ignoring the captured output, e.g.:
import subprocess
rc = subprocess.call(['grep', 'pattern', 'file'],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
...
elif rc == 1: # not found
...
elif rc > 1: # error
...
You don't need shell=True
to run the commands from your question.
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
gtools/smartbind didnt like working with Dates, probably because it was as.vectoring. So here's my solution...
sbind = function(x, y, fill=NA) {
sbind.fill = function(d, cols){
for(c in cols)
d[[c]] = fill
d
}
x = sbind.fill(x, setdiff(names(y),names(x)))
y = sbind.fill(y, setdiff(names(x),names(y)))
rbind(x, y)
}
public static String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
If you give each of these instances a class you can use
$('.yourClass').upload()
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
You can use localStorage
for the purpose.
Steps:
Perl solution:
perl -lane 'splice @F,0,2; print join " ",@F' file
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-e
execute the perl code
splice @F,0,2
cleanly removes columns 0 and 1 from the @F array
join " ",@F
joins the elements of the @F array, using a space in-between each element
If your input file is comma-delimited, rather than space-delimited, use -F, -lane
Python solution:
python -c "import sys;[sys.stdout.write(' '.join(line.split()[2:]) + '\n') for line in sys.stdin]" < file
let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)
On my Mac that I'm sure I'm not going to allow java anyplace other than a specific site, I was able to use Preferences->Java to bring up the Java control panel and turned the checking off. If DLink ever fixes their certificate, I'll turn it back on.
It's pretty straightforward, using jdk6 at least...
bash$ keytool -keystore foo.jks -genkeypair -alias foo \ -dname 'CN=foo.example.com,L=Melbourne,ST=Victoria,C=AU' Enter keystore password: Re-enter new password: Enter key password for (RETURN if same as keystore password): bash$ keytool -keystore foo.jks -exportcert -alias foo | \ openssl x509 -inform der -text Enter keystore password: asdasd Certificate: Data: Version: 3 (0x2) Serial Number: 1237334757 (0x49c03ae5) Signature Algorithm: dsaWithSHA1 Issuer: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Validity Not Before: Mar 18 00:05:57 2009 GMT Not After : Jun 16 00:05:57 2009 GMT Subject: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Subject Public Key Info: Public Key Algorithm: dsaEncryption DSA Public Key: pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7: bash$ keytool -importkeystore -srckeystore foo.jks \ -destkeystore foo.p12 \ -srcstoretype jks \ -deststoretype pkcs12 Enter destination keystore password: Re-enter new password: Enter source keystore password: Entry for alias foo successfully imported. Import command completed: 1 entries successfully imported, 0 entries failed or cancelled bash$ openssl pkcs12 -in foo.p12 -out foo.pem Enter Import Password: MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase: bash$ openssl x509 -text -in foo.pem Certificate: Data: Version: 3 (0x2) Serial Number: 1237334757 (0x49c03ae5) Signature Algorithm: dsaWithSHA1 Issuer: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Validity Not Before: Mar 18 00:05:57 2009 GMT Not After : Jun 16 00:05:57 2009 GMT Subject: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Subject Public Key Info: Public Key Algorithm: dsaEncryption DSA Public Key: pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7: bash$ openssl dsa -text -in foo.pem read DSA key Enter PEM pass phrase: Private-Key: (1024 bit) priv: 00:8f:b1:af:55:63:92:7c:d2:0f:e6:f3:a2:f5:ff: 1a:7a:fe:8c:39:dd pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7:
You end up with:
(This last file can be split up into keys and certificates if you like.)
Command summary - to create JKS keystore:
keytool -keystore foo.jks -genkeypair -alias foo \
-dname 'CN=foo.example.com,L=Melbourne,ST=Victoria,C=AU'
Command summary - to convert JKS keystore into PKCS#12 keystore, then into PEM file:
keytool -importkeystore -srckeystore foo.jks \
-destkeystore foo.p12 \
-srcstoretype jks \
-deststoretype pkcs12
openssl pkcs12 -in foo.p12 -out foo.pem
if you have more than one certificate in your JKS keystore, and you want to only export the certificate and key associated with one of the aliases, you can use the following variation:
keytool -importkeystore -srckeystore foo.jks \
-destkeystore foo.p12 \
-srcalias foo \
-srcstoretype jks \
-deststoretype pkcs12
openssl pkcs12 -in foo.p12 -out foo.pem
Command summary - to compare JKS keystore to PEM file:
keytool -keystore foo.jks -exportcert -alias foo | \
openssl x509 -inform der -text
openssl x509 -text -in foo.pem
openssl dsa -text -in foo.pem
let cloned = JSON.parse(JSON.stringify(objectToClone));
Why? this method will convert 'function,undefined' to null
const myObj = [undefined, null, function () {}, {}, '', true, false, 0, Symbol];
const IsDeepClone = JSON.parse(JSON.stringify(myObj));
console.log(IsDeepClone); //[null, null, null, {…}, "", true, false, 0, null]
try to use deepClone function.There are several above
I've really read a lot of great answers!
Here is my 2 cent: build a statistical model of the memory/register abnormality, by writing a software to check the memory or to perform frequent register comparisons. Further, create an emulator, in the style of a virtual machine where you can experiment with the issue. I guess if you vary junction size, clock frequency, vendor, casing, etc would observe a different behavior.
Even our desktop PC memory has a certain rate of failure, which however doesn't impair the day to day work.
I use this which is standard for every time
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
I'd use a UIViewController subclass containing a "Container View" that embeds your others view controllers. You'll then be able to add the navigation controller inside the Container View (using the embed relationship segue for example).
Very simple avoid using DateTime.MinValue
use System.Data.SqlTypes.SqlDateTime.MinValue
instead.
First make your template into a jQuery object:
var template = $("<li><div class='bar'>bla</div></li>");
Then set the attributes and append it to the DOM.
template.find('li').attr('id','1234');
$(document.body).append(template);
Note that it however makes no sense at all to add a li directly to the DOM since li should always be children of ul or ol. Also it is better to not make jQuery parse raw HTML. Instead create a li, set its attributes. Create a div and set it's attributes. Insert the div into the li and then append the li to the DOM.
if (-e $base_path)
{
# code
}
-e
is the 'existence' operator in Perl.
You can check permissions and other attributes using the code on this page.
We all know that PHP save errors in php_errors.log file.
But, that file contains a lot of data.
If we want to log our application data, we need to save it to a custom location.
We can use two parameters in the error_log function to achieve this.
http://php.net/manual/en/function.error-log.php
We can do it using:
error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');
Where,
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
3
: Put log message to custom log file specified in the third parameter.
'/var/tmp/errors.log'
: Custom log file (This path is for Linux, we can specify other depending upon OS).
OR, you can use file_put_contents()
file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);
Where:
'/var/tmp/errors.log':
Custom log file (This path is for Linux, we can specify other depending upon OS).
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.
I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css
file was written after the media queries
. when I moved it above media queries it started working.
Just in case someone else is facing the same problem
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
The solution, if your list items can be display: inline
is quite easy:
#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }
However, many times you must use display:block
on your <li>
s. The following CSS will work, in this case:
#footer { width: 100%; overflow: hidden; }
#footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; }
#footer ul li { position: relative; float: left; display: block; right: 50%; }
You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor
<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
...
<item name="android:windowMinWidthMajor">97%</item>
<item name="android:windowMinWidthMinor">97%</item>
</style>
NSString * str = [componentsJoinedByString:@""];
and you have dic or multiple array then used bellow
NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
What about:
git reset
back to the last commit before you started making changes.git pull
to re-pull just the remote changes you threw away with the reset.Or will that explode when you try to re-merge the branch?
The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T>
and a T[]
can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.
For example, suppose you have a List<string>
and wish to have every string in the list which starts with T
be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:
int srcPtr,destPtr;
string[] arr;
srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
string st = arr[srcPtr];
char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
if (ch != 'U')
arr[destPtr++] = st;
if (ch == 'T')
arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
theList = new List<String>(arr); // Adds extra elements
if (destPtr != arr.Length)
theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
Array.Resize(ref arr, destPtr);
theList = new List<String>(arr); // Adds extra elements
}
It would have been helpful if List<T>
provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.
$('form[name="frmSave"]')
is correct. You mentioned you thought this would get all children with the name frmsave
inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');
$('form[name="frmSave"]')
literally means find all forms with the name frmSave
, because there is no combinator involved.
Since Python evaluates also the data type NoneType
as False
during the check, a more precise answer is:
var = False
if var is False:
print('learnt stuff')
This prevents potentially unwanted behaviour such as:
var = [] # or None
if not var:
print('learnt stuff') # is printed what may or may not be wanted
But if you want to check all cases where var
will be evaluated to False
, then doing it by using logical not
keyword is the right thing to do.
The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.
Here's a cut and paste of the code, which worked for me:
function countProperties(obj) {
var prop;
var propCount = 0;
for (prop in obj) {
propCount++;
}
return propCount;
}
This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.
Simply updated Xcode. Solved my problem
Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.
Sample: (It's shown in Portuguese, but it also works in english and italian).
Before you can use this lib, you have to implement a class named MsvAuthority
inside the br.com.mauker
package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY
. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.
Example:
MsvAuthority.java
package br.com.mauker;
public class MsvAuthority {
public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<application ... >
<provider
android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
android:exported="false"
android:protectionLevel="signature"
android:syncable="true"/>
</application>
</manifest>
To use it, add the dependency:
compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'
And then, on your Activity
layout file, add the following:
<br.com.mauker.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
After that, you'll just need to get the MaterialSearchView
reference by using getViewById()
, and open it up or close it using MaterialSearchView#openSearch()
and MaterialSearchView#closeSearch()
.
P.S.: It's possible to open and close the view not only from the Toolbar
. You can use the openSearch()
method from basically any Button
, such as a Floating Action Button.
// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.openSearch();
}
});
You can also close the view using the back button, doing the following:
@Override
public void onBackPressed() {
if (searchView.isOpen()) {
// Close the search on the back button press.
searchView.closeSearch();
} else {
super.onBackPressed();
}
}
For more information on how to use the lib, check the github page.
can this help?
select
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d
For compatibility with all browsers stick with .ico
.
.png is getting more and more support though as it is easier to create using multiple programs.
for .ico
<link rel="shortcut icon" href="http://example.com/myicon.ico" />
for .png, you need to specify the type
<link rel="icon" type="image/png" href="http://example.com/image.png" />
May 2017; I had the same issue, could not even get to apps as it just cycled between starting and stopping. Went into avd settings, edited the multi core (unticked the box) and set graphics to software Gles. It appears to have fixed the issue
To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
I prefer something like the following:
type StringRef []byte
func (s StringRef) String() string {
return string(s[:])
}
…
// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))
You can use JsonBuilder for that.
Example Code:
import groovy.json.JsonBuilder
class Person {
String name
String address
}
def o = new Person( name: 'John Doe', address: 'Texas' )
println new JsonBuilder( o ).toPrettyString()